我正在做一个项目,但在 UI 方面遇到了很多障碍。 在这种情况下,创建一个新线程来更新 UI,以便 UI 主线程保持打开状态,让您仍然可以使用 UI。
我不确定这是什么问题。我想也许我正在使用调度程序创建线程而不是创建线程使用主线程?还值得注意的是,我的 MainWindow 是单例实例。
private void button_Click(object sender, RoutedEventArgs e)
{
if (go)
{
city = textBox.GetLineText(0);
if (city == "exit")
{
Environment.Exit(0);
}
Thread t1 = new Thread(new ThreadStart(
delegate
{
this.Dispatcher.Invoke(DispatcherPriority.Background, new Action(start));
}));
t1.Start();
//await Task.Run(() => start());
}
}
请您参考如下方法:
您不需要创建新线程。当您使用 async 和 await 时,将自动从线程池中分配一个新线程。只需按照下面的代码中所述使您的 button_Click 事件处理程序异步,并使用 await 关键字调用长时间运行的任务。
private async void button_Click(object sender, RoutedEventArgs e)
{
if (go)
{
city = textBox.GetLineText(0);
if (city == "exit")
{
Environment.Exit(0);
}
await Task.Run(() => start());
}
}
这里会发生什么,当你点击按钮时,事件就会被处理。如果满足条件,则在此行 await Task.Run(() => start()); 中启动长时间运行的任务。然后它将返回到 UI 线程而不阻塞它,即当另一个线程在后台执行长时间运行的进程时,UI 仍然会响应。
请阅读Asynchronous Programming with async and await (C#) on MSDN.
编辑: 由于您想在 start() 方法中控制 UI 元素,请使用以下方法:
private async void button_Click(object sender, RoutedEventArgs e)
{
if (go)
{
city = textBox.GetLineText(0);
if (city == "exit")
{
Environment.Exit(0);
}
await start();
}
}
private async Task start()
{
await Task.Run(async () =>
{
// long running task here
});
// UI Control code here.
}
