问题描述
这是我的第一个问题.由于英语不是我的母语,所以请您原谅我的错误.
This is my first question here. As English is not my first language, forgive me for any mistakes.
我正在尝试为Windows Phone 8.1(XAML和C#)开发应用程序,并且正在使用.NET Framework 4.5.2.我刚刚开始研究C#中的多线程,如果能有人帮助我,我将不胜感激.到目前为止,我发现的所有相关问题的答案都太复杂了.
I'm trying to develop an application for Windows Phone 8.1 (XAML and C#) and I'm using .NET Framework 4.5.2.I just started studying multithreading in C# and would appreciate if anyone here could help me. All answers to related questions I've found so far are too complex.
我所需要做的就是通过单击按钮创建一个新任务,该任务将在文本块控件中显示一条消息.
All I need is to create a new task from a button click that displays a message in a textblock control.
private void myButton_Click(object sender, RoutedEventArgs e)
{
Task t = new Task(MyMethod);
t.Start();
}
private void MyMethod()
{
myTextBlock.Text = "Worked!";
}
我收到以下异常:该应用程序调用了一个已编组用于另一个线程的接口. (来自HRESULT的异常:0x8001010E(RPC_E_WRONG_THREAD)).
I'm getting the following exception: The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD)).
我该如何纠正?
提前谢谢!
推荐答案
如果您使用async/await编程模型,则可以很容易地做到这一点.
If you use the async/await programming model, you could do this quite easily.
请尝试以下操作,而不是您拥有的内容:
Instead of what you have, try something like this:
private async void myButton_Click(object sender, RoutedEventArgs e)
{
Task t = MyMethod();
await t;
}
private async Task MyMethod()
{
myTextBlock.Text = "Worked!";
}
这篇关于从其他线程更新UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!