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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#多线程の多个线程处理一个任务,然后执行其余相关的知识,希望对你有一定的参考价值。


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#多线程の多个线程处理一个任务,然后执行其余的主要内容,如果未能解决你的问题,请参考以下文章

java 一个线程处理多个任务

C# 线程基础

.net开发中,为何将100多个任务放入线程池却只有一个线程顺序执行

C#中定时器执行定时器触发任务是单线程还是多线程?

C#多线程处理多个队列数据的方法

C#多线程: 怎么知道 多个线程 执行完毕了?所有的线程执行完毕后 我要做处理