I'm implementing an interface with the async method Execute
. In this I need to call some synchronous code. (removing an item from a dictionary). What would be the best way to go about this?
Alternative 1.
internal class ClearClaimByClaimIdCache : IListenTo<ClaimStatusChangedEvent>
{
private readonly ICache<Guid, Claim> _cache;
public ClearClaimByClaimIdCache(ICacheFactory cacheFactory)
{
_cache = cacheFactory.GetOrCreateCache<Guid, Claim>("ClaimByClaimId");
}
public Task Execute(ClaimStatusChangedEvent @event)
{
_cache.Remove(@event.ClaimId);
return Task.CompletedTask;
}
}
Alternative 2.
public Task Execute(ClaimStatusChangedEvent @event)
{
return Task.Run(() => _cache.Remove(@event.ClaimId));
}
Alternative 3.
public async Task Execute(ClaimStatusChangedEvent @event)
{
await Task.Run(() => _cache.Remove(@event.ClaimId));
}
Or any better way?
await
does). If you were composing multiple actions inside of that method then I'd maybe say yes, use await, but otherwise just return the Task. \$\endgroup\$ – Dan Nov 5 '15 at 11:03Task
-returning method is not the same as calling a callback synchronously. For example, theTask
method returns before the caller continues, so it won't have anything on the call stack. \$\endgroup\$ – svick Nov 5 '15 at 12:52