Home >Backend Development >C++ >How to Catch Exceptions from Separate Threads in .NET?

How to Catch Exceptions from Separate Threads in .NET?

Linda Hamilton
Linda HamiltonOriginal
2025-01-05 06:54:39634browse

How to Catch Exceptions from Separate Threads in .NET?

Catch Exceptions Thrown in a Separate Thread

In multithreaded applications, it's crucial to handle exceptions that occur in separate threads. This guide will demonstrate two approaches to accomplish this.

Task-Based Exception Handling in .NET 4 and Above

Consider using Task instead of creating new threads. With Task, exceptions can be retrieved via the .Exceptions property. Here are two ways to do it:

  • In a Separate Method:
Task<int> task = new Task<int>(Test);
task.ContinueWith(ExceptionHandler, TaskContinuationOptions.OnlyOnFaulted);
task.Start();
...

static void ExceptionHandler(Task<int> task)
{
    Console.WriteLine(task.Exception.Message);
}
  • In the Same Method:
Task<int> task = new Task<int>(Test);
task.Start();

try
{
    task.Wait();
}
catch (AggregateException ex)
{
    Console.WriteLine(ex);
}

Exception Handling in .NET 3.5

For .NET 3.5, consider the following approaches:

  • In the Child's Thread:
Exception exception = null;
Thread thread = new Thread(() => Test(0, 0));
thread.Start();

thread.Join();

if (exception != null)
    Console.WriteLine(exception);
  • In the Caller's Thread:
Exception exception = null;
Thread thread = new Thread(() =>
{
    try
    {
        Test(0, 0);
    }
    catch (Exception ex)
    {
        lock (exceptionLock)
        {
            exception = ex;
        }
    }
});
thread.Start();
thread.Join();

if (exception != null)
    Console.WriteLine(exception);

The above is the detailed content of How to Catch Exceptions from Separate Threads in .NET?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn