I am toying around with an async service for a Windows 8 project and there are some async calls of this service, which should only be called once at a time.
public async Task CallThisOnlyOnce()
{
PropagateSomeEvents();
await SomeOtherMethod();
PropagateDifferentEvents();
}
Since you cannot encapsulate an async call in a lock statement, i thought of using the AsyncLock
pattern, but than i thought i might as well try something like this:
private Task _callThisOnlyOnce;
public Task CallThisOnlyOnce()
{
if(_callThisOnlyOnce != null && _callThisOnlyOnce.IsCompleted)
_callThisOnlyOnce = null;
if(_callThisOnlyOnce == null)
_callThisOnlyOnce = CallThisOnlyOnceAsync();
return _callThisOnlyOnce;
}
private async Task CallThisOnlyOnceAsync()
{
PropagateSomeEvents();
await SomeOtherMethod();
PropagateDifferentEvents();
}
Therefore you would end up with the call CallThisOnlyOnceAsync
only executed once simultanously, and multiple awaiters hooked on the same Task.
Is this a "valid" way of doing this or are there some drawbacks to this approach?
See Question&Answers more detail:os