简体   繁体   English

如何强制任务触发跨线程异常

[英]How to force Task fire cross-thread exception

I have just updated the Visual Studio to 17.4.4.我刚刚将 Visual Studio 更新到 17.4.4。

In the following code Thread fires cross-thread exception but Task doesn't.在下面的代码中,Thread 触发了跨线程异常,但 Task 没有。 In the Start Without Debugging, Task still does nothing and Thread halts the application.在 Start Without Debugging 中,Task 仍然什么也不做,Thread 停止了应用程序。

How to force Task fires cross-thread exception not to miss it?如何强制Task触发跨线程异常不遗漏呢?

public Form1()
{
    InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
    CheckForIllegalCrossThreadCalls = true;
}

private void button1_Click(object sender, EventArgs e)
{
    Task task = new(Method1);

    task.Start(); // does not change Text and does not fire exception
}

private void button2_Click(object sender, EventArgs e)
{
    Thread thread = new(Method1);

    thread.Start(); // fires exception
}

void Method1()
{
    Text = "a";
}

This is by design.这是设计使然。 When a Task fails, the exception is captured in its Exception property.Task失败时,异常会在其Exception属性中捕获。 The error is not propagated as an unhandled exception that crashes the process.该错误不会作为使进程崩溃的未处理异常传播。 In case you find the process-crashing behavior desirable, you can make it happen by await ing the task on the ThreadPool :如果您发现进程崩溃行为是可取的,您可以通过await ThreadPool上的任务来实现它:

ThreadPool.QueueUserWorkItem(async _ => await task);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM