码迷,mamicode.com
首页 > 编程语言 > 详细

C#多线程の多个线程处理一个任务,然后执行其余

时间:2017-09-13 20:23:17      阅读:270      评论:0      收藏:0      [点我收藏+]

标签:logs   rod   consumer   received   oid   sleep   listener   star   ret   


In the comments, I was 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

        //call callback 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 have a huge object hosting messages ConcurrentList<string>, task pushes a message ‘OnCompleted‘ to the object, on the other side, a listener subscribes the message, once a OnCompleted received, it will execute the continuation.

C#多线程の多个线程处理一个任务,然后执行其余

标签:logs   rod   consumer   received   oid   sleep   listener   star   ret   

原文地址:http://www.cnblogs.com/xietianjiao/p/7517251.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!