C # Multithreading multiple threads handles one task and then executes the rest

Source: Internet
Author: User


In the comments, I is told that I should avoid thread.sleep (), all right, let's try this:
1. You could wrap the Parallel.ForEach within a task and manually add your Completedcallback ()
 Public Task Doworkasync (doworkcompletedcallback completedcallback) {    return  Task.Factory.StartNew (    {         Parallel.ForEach        //callcallback manually         Completedcallback ();    });}

2. Use ContinueWith
Task.Factory.StartNew (    {         //do work    }    ). ContinueWith (completedcallback);


3. You could assign callback in the caller, it ' s the same as 2.
Task NewTask = Task.Factory.StartNew (    {         //do work}); Newtask.continuewith (oncompleted);

4. Consumer-publisher Patterns
Producer Consumer problem

Assume you has a huge object hosting messages Concurrentlist<string>, task pushes a message ' oncompleted ' to the OB Ject, on the other side, a listener subscribes the message, once a oncompleted received, it'll execute the continuation.

C # Multithreading multiple threads handles one task and then executes the rest

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.