SoFunction
Updated on 2025-03-01

Common operational misunderstandings and exception handling of C# multi-threaded TPL

1. Must async to the end

We must make the contagious async (you need to use await to call asynchronous methods, and the method that uses await must be declared as async. The place where I call this async method must be await...) Don't call Task's Wait, WaitAll and other methods directly. Wait for one to use await, not (); wait for multiple to use await (), not (.

2. The performance of asynchronous use may not be high

The performance of async in the program does not necessarily mean that the performance is high, and the following asynchronous method is meaningless:

public async Task<string> GetAsync()
{
    return await <string>(() => 
    {
        using (WebClient client = new WebClient())
        {
            // The synchronous method is used here, so the asynchronous method has no meaning            return ("");
        }
    });
}

The synchronization method is called in Task, so there is no point in it.

After using asynchronous, you can use the asynchronous API, use the asynchronous API, only use await and WhenAll, do not use Wait().

, IO, EF, etc. all provide asynchronous APIs.

Exception handling in TPL

1. In TPL, if an exception occurs in the program, unless you use try...catch to catch the exception, you will not feel that an exception occurs.

2. TPL programs sometimes throw AggregateException, which usually occurs when multiple tasks are executed in parallel. Because multiple parallel tasks may experience multiple exceptions, they will be wrapped as an AggregateException exception. The InnerException property of AggregateException can obtain information about multiple exception objects. See the following code:

private void button1_Click(object sender, EventArgs e)
{
    try
    {
        HttpClient hc = new HttpClient();
        // Existing URL address        string url1 = "";
        // Non-existent URL        string url2 = "http://";
        string url3 = "http://";
        var task1 = (url1);
        var task2 = (url2);
        var task3 = (url3);
        // Perform three tasks in parallel        (task1, task2, task3);
        ("Download successfully");
       
    }
    catch (AggregateException ae)
    {
        // Loop traversal output exception information        foreach (var item in )
        {
            ();
        }
    }
}

When running the program, multiple exception information will be output cycleically.

This is what this article about common operational misunderstandings and exception handling of C# multi-threaded TPL mode is introduced. I hope it will be helpful to everyone's learning and I hope everyone will support me more.