[英]Async wait for multiple threads to finish
I have a code block which is eventually accessed by multiple threads. 我有一个代码块,最终可以被多个线程访问。 I search for an up to date async mechanism to continue executing when all threads have passed.
我搜索了最新的异步机制,以在所有线程通过后继续执行。
Currently I do the following with a CountDownEvent which works just fine (without async support). 目前,我使用CountDownEvent进行以下操作,该方法工作正常(没有异步支持)。
public class Watcher
{
private static readonly Logger Log = LogManager.GetCurrentClassLogger();
private readonly CountdownEvent _isUpdating = new CountdownEvent(1);
private readonly IActivity _activity;
public Watcher([NotNull] IActivity activity)
{
_activity = activity ?? throw new ArgumentNullException(nameof(activity));
_activity.Received += OnReceived;
}
private void OnReceived(IReadOnlyCollection<Summary> summaries)
{
_isUpdating.AddCount();
try
{
// Threads processing
}
finally
{
_isUpdating.Signal();
}
}
private void Disable()
{
_activity.Received -= OnReceived;
_isUpdating.Signal();
/* await */ _isUpdating.Wait();
}
}
Do I need to use any of those AsyncCountdownEvent implementations or is there any other built-in mechanism? 我是否需要使用任何这些AsyncCountdownEvent实现,或者是否有其他内置机制? I already thought about using a BufferBlock because it has async functionality but I think it's a bit overkill.
我已经考虑过使用BufferBlock,因为它具有异步功能,但是我认为这有点过头了。
Additional to the comments: 注释的补充:
IActivity is a WebService call (but shouldn't effect the implementation on top or vice versa) IActivity是一个WebService调用(但不应首先影响实现,反之亦然)
public async Task Start(bool alwayRetry = true, CancellationToken cancellationToken = new CancellationToken())
{
var milliseconds = ReloadSeconds * 1000;
do
{
try
{
var summaries = await PublicAPI.GetSummariesAsync(cancellationToken).ConfigureAwait(false);
OnSummariesReceived(summaries);
}
catch (Exception ex)
{
Log.Error(ex.Message);
OnErrorOccurred(ex);
}
await Task.Delay(milliseconds, cancellationToken).ConfigureAwait(false);
// ReSharper disable once LoopVariableIsNeverChangedInsideLoop
} while (alwayRetry);
}
It's not clear the IActivity
signatures; 目前尚不清楚
IActivity
签名; but you can wait for a range of tasks to be completed: 但您可以等待一系列任务完成:
class MultiAsyncTest {
Task SomeAsync1() { return Task.Delay(1000); }
Task SomeAsync2() { return Task.Delay(2000);}
Task EntryPointAsync() {
var tasks = new List<Task>();
tasks.Add(SomeAsync1());
tasks.Add(SomeAsync2());
return Task.WhenAll(tasks);
}
}
What's IActivity
's signature? IActivity
的签名是什么? Does it support Task
? 它支持
Task
吗? Or you are using Thread
? 或者您正在使用
Thread
? More explanation would help to a more specified answer. 更多的解释将有助于获得更明确的答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.