HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Calling synchronous code in asynchronous method

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
methodsynchronousasynchronouscodecalling

Problem

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
{
        private readonly ICache _cache;

        public ClearClaimByClaimIdCache(ICacheFactory cacheFactory)
        {
            _cache = cacheFactory.GetOrCreateCache("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?

Solution

If it's really just removing an item from a dictionary (and not e.g. doing synchronous file IO), then Alternative 1 is the best.

When you're using async for scalability (e.g. in ASP.NET), using Task.Run() like this won't help you (since the number of threads used stays the same), it will only hurt you a bit (since Task.Run() has some overhead).

When you're using async for responsiveness (e.g. in GUI applications), using Task.Run() like this can make sense, but only for long-running operations (MS recommendation is operations that can take more than 50 ms). Since dictionary operations shouldn't take long you shouldn't use Task.Run() here either.

Context

StackExchange Code Review Q#109864, answer score: 12

Revisions (0)

No revisions yet.