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

How to Catch Exceptions from Separate Threads in .NET?

Linda Hamilton
Release: 2025-01-05 06:54:39
Original
572 people have browsed it

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);
}
Copy after login
  • In the Same Method:
Task<int> task = new Task<int>(Test);
task.Start();

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

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);
Copy after login
  • 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);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template