Asynchronous programming exception and deadlock handling, asynchronous programming

Source: Internet
Author: User

Asynchronous programming exception and deadlock handling, asynchronous programming

 

In. NET asynchronous programming, async and await are usually used as prime partners, and the return type uses Task or Task <T>. Add async before the method to indicate that the method runs asynchronously, and use await in the method to execute an asynchronous wait.

 

The following is a simple example:

 

        static void Main(string[] args)
        {
            Doth();
            Console.ReadKey();
        }
        static async Task Doth()
        {
            int i = 2;
            await Task.Delay(TimeSpan.FromSeconds(2));
            i += 2;
            await Task.Delay(TimeSpan.FromSeconds(2));
            Console.WriteLine(i);
        }

 

When the dosomething method is executed, the first await executes an asynchronous wait. When the execution is completed, the following code is executed. Within the async modification method, an await is an asynchronous wait that can contain multiple await instances. After each await instance is executed, the code behind it is executed, that is, it is synchronized within dosomething.

 

In which thread does each await run?

 

By default, it runs in the current thread. However,. NET provides the ConfigureAwait method to set the thread in which await runs.

 

        static async Task Doth()
        {
            int i = 2;
            await Task.Delay(TimeSpan.FromSeconds(2)).ConfigureAwait(false);
            i += 2;
            await Task.Delay(TimeSpan.FromSeconds(2)).ConfigureAwait(false);
            Console.WriteLine(i);
        }

 

Above, when the first await runs in the thread where the console project is located, the second await runs in the thread pool.

 

We cannot guarantee that each await will not throw an exception. We usually catch the exception as follows.

 

async Task DosthAsync()
{
    try
    {
        await PossibleExceptionAsync();
    }
    catch(NotSuppotedException ex)
    {
        LogException(ex);
        throw;
    }
}

 

Because the thrown exception will be placed in the Task object, you can also write it like this:

 

async Task DosthAsync()
{
    Task task = PossibleExceptionAsync();
    try
    {
        await task;
    }
    cach(NotSupportedException ex)
    {
        LogException(ex);
        throw;
    }
}

 

Asynchronous programming also causes deadlocks.

 

async Task DoSthSync()
{
    await Task.Delay(TimeSpan.FromSeconds(1));
}
void FirstThing()
{
    Task tak = DoSthSync();
    task.Wait();
}

 

If you call the FirstThing method, a deadlock occurs.

 

→ Execute the FirstThing Method
→ Execute the DoSthSync method inside the FirstThing method. At this time, the current context thread is blocked.
→ In the DoSthSync method, await tries to capture the current context thread, and the current upstream and downstream threads are blocked, causing a deadlock.

 

How can deadlocks be solved?

 

You can use the thread in the thread pool instead of the current context thread in DoSthSync. The modifications are as follows:

 

async Task DoSthSync()
{
    await Task.Delay(TimeSpan.FromSeconds(1)).ConfigureAwait(false);
}

 

Or, convert FirstThing into an Asynchronous Method. Modify as follows:

 

async Task DoSthSync()
{
    await Task.Delay(TimeSpan.FromSeconds(1));
}
async Task FirstThing()
{
    await DoSthSync();
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.