Home > Software engineering >  How to force Task fire cross-thread exception
How to force Task fire cross-thread exception

Time:01-11

I have just updated the Visual Studio to 17.4.4.

In the following code Thread fires cross-thread exception but Task doesn't. In the Start Without Debugging, Task still does nothing and Thread halts the application.

How to force Task fires cross-thread exception not to miss it?

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";
}

CodePudding user response:

This is by design. When a Task fails, the exception is captured in its Exception property. 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 awaiting the task on the ThreadPool:

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