【问题标题】:Why is Task.Wait() causing application to freeze为什么 Task.Wait() 导致应用程序冻结
【发布时间】:2017-08-12 01:43:16
【问题描述】:

当我调用 BuildCustomer.StartTask 时,我会调用一个方法 WriteToDatabase。在 WriteToDatabase 中,我想将状态发送回 MainForm 以将状态写入 GUI。当代码达到那个点时,我的应用程序会冻结并且没有错误。我确实发现如果我删除 task.Wait(),它会停止冻结并工作。但我想我想要等待,因为我的 BuildCustomer 需要一些时间并将大量更新(包括来自 Common 类的更多更新)写入 GUI。有人可以告诉我哪里出了问题或者我应该做些什么不同的事情吗?这是一个 .Net 4 项目,所以我不能使用异步,我已经看到了其他答案。

public partial class MainForm : Window
{
    public MainForm()
    {
        Common.SendMessage += UpdateStatus;
    }

    private void Button_Click(object sender, EventArgs e)
    {
        BuildCustomer.StartTask();
    }

    private void UpdateStatus(string message)
    {
        Dispatcher.Invoke(new Action(() =>
        {
            StatusTextBox.Text = message;
        }));
    }
}

public class BuildCustomer
{
    public static void StartTask()
    {
        var action = new Action<object>(BuildCustomer);

        var task = new Task(() => action(buildDetails));

        task.Start();

        task.Wait();
    }

    private void BuildCustomerDetails(object buildDetails)
    {
        Common.WriteToDatabase();
    }
}

public class Common
{
    public delegate void MessageLogDelegate(string message);

    public static event MessageLogDelegate SendMessage;

    public static void WriteToDatabase()
    {
        SendMessage("Some status message to write back to the GUI");
    }
}

【问题讨论】:

标签: c# async-await task-parallel-library


【解决方案1】:

你有一个死锁。 StartTask 等待 task.Wait() 完成,但这会在主 UI 线程的调用线程上发生(被调用)。

正在等待的 Task 最终到达 UpdateStatus,它也在 UI 线程上调用 Invoke,但该线程当前正在等待 task.Wait()因此它是阻塞的,导致 UI 线程不被无限期可用)。

【讨论】:

  • 感谢您的解释。
【解决方案2】:

尝试在方法签名中添加 async 关键字并使用:

await task;

导致主线程(UI线程)不休眠。

【讨论】:

  • 如果没有我做不到的附加组件,异步在 4.0 中不可用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-18
  • 1970-01-01
  • 1970-01-01
  • 2022-12-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多