2

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";
}
SHIN JaeGuk
  • 494
  • 1
  • 5
  • 14
  • [Don't ever create a Task and call Start() unless you find an extremely good reason to do so](https://stackoverflow.com/a/29693430/6196568). Use await to call an async method, that will handle the exception for you: [How do i call an async method from a winforms button click event?](https://stackoverflow.com/questions/51664291/how-do-i-call-an-async-method-from-a-winforms-button-click-event) – shingo Jan 11 '23 at 09:43

1 Answers1

1

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);
Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104