c# – 异步/等待任务和WaitHandle
作者:互联网
假设我有10N个项目(我需要通过http协议获取它们),在代码中N任务开始获取数据,每个任务按顺序排列10个项目.我将这些项目放在ConcurrentQueue< Item>中.之后,逐个线程不安全地处理项目.
async Task<Item> GetItemAsync()
{
//fetch one item from the internet
}
async Task DoWork()
{
var tasks = new List<Task>();
var items = new ConcurrentQueue<Item>();
var handles = new List<ManualResetEvent>();
for i 1 -> N
{
var handle = new ManualResetEvent(false);
handles.Add(handle);
tasks.Add(Task.Factory.StartNew(async delegate
{
for j 1 -> 10
{
var item = await GetItemAsync();
items.Enqueue(item);
}
handle.Set();
});
}
//begin to process the items when any handle is set
WaitHandle.WaitAny(handles);
while(true)
{
if (all handles are set && items collection is empty) //***
break;
//in another word: all tasks are really completed
while(items.TryDequeue(out item))
{
AThreadUnsafeMethod(item); //process items one by one
}
}
}
我不知道如果条件可以放在标有***的声明中.我不能在这里使用Task.IsCompleted属性,因为我在任务中使用await,因此任务很快就完成了.并且指示任务是否执行到最后的bool []看起来真的很难看,因为我认为ManualResetEvent可以做同样的工作.任何人都可以给我一个建议吗?
解决方法:
好吧,你可以自己构建,但我认为TPL Dataflow更容易.
就像是:
static async Task DoWork()
{
// By default, ActionBlock uses MaxDegreeOfParallelism == 1,
// so AThreadUnsafeMethod is not called in parallel.
var block = new ActionBlock<Item>(AThreadUnsafeMethod);
// Start off N tasks, each asynchronously acquiring 10 items.
// Each item is sent to the block as it is received.
var tasks = Enumerable.Range(0, N).Select(Task.Run(
async () =>
{
for (int i = 0; i != 10; ++i)
block.Post(await GetItemAsync());
})).ToArray();
// Complete the block when all tasks have completed.
Task.WhenAll(tasks).ContinueWith(_ => { block.Complete(); });
// Wait for the block to complete.
await block.Completion;
}
标签:c,asynchronous,async-await,task,waithandle 来源: https://codeday.me/bug/20190626/1288905.html