UI 即使使用多线程仍被锁定

UI still locked up even with multi threading

我正在做一个项目,我遇到了很多 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());这一行启动长运行任务。然后它会 return 到 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.
}