Callback of TPL asynchronous parallel programming

Source: Internet
Author: User
Tags call back

Task is a highly asynchronous multithreaded programming based on the threadpool thread pool, and if one day I want a task that needs to run for a long time, you can call back some code after being terminated by some exception to know why the task terminated.

Yes, and look at the code.

public static Task Asyncrun (this iloggerprovider logprovider, Action Task, TaskCreationOptions taskoption, action< Exception> Exceptionhandler)
{
Return Task.Factory.StartNew (Task, taskoption). ContinueWith (t =
{
if (Exceptionhandler! = null)
Exceptionhandler (t.exception);
Else
{
if (logProvider.Logger.IsErrorEnabled)
{
for (var i = 0; i < T.exception.innerexceptions.count; i++)
{
LogProvider.Logger.Error (T.exception.innerexceptions[i]);
}
}
}
}, taskcontinuationoptions.onlyonfaulted);
}

Task.Factory.StartNew (() =>{

while (true) {

A thread that continues to work

}

}). ContinueWith (t=>{

I am the tail of this thread because the thread will call me when it is terminated for some reason, where I can handle exceptions, and other things

such as anomalies.

var exception=t.exception;//at this point I can get to the outside or log out of the cause of the abnormal termination

})

At the same time, you can also set the thread by Taskcontinuationoptions what happens before the callback code

So task is really handy and efficient, and it's very useful for server multithreaded programming, rather than the traditional direct new thread that keeps the thread running, the server's thread will reach a very high value and slow down the process performance because the thread will have a lot of resource overhead. , especially for systems with frequent IO.

Callback of TPL asynchronous parallel programming

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.