BardMorgan
BardMorgan

Reputation: 454

How do I create an async overload of an existing synchronous method?

I have several libraries that currently don't support async/await and I'm trying to update them. For methods that can call existing async code (such as using File.ReadAllLinesAsync instead of File.ReadAllLines) creating an async overload is pretty easy. However, for methods that don't call other code that has asynchronous capabilities, the overload is not so easy.

As an example, Let's say I have a method as follows:

public ResultType DoLotsOfStuff(string p1, string p2)
{
   ResultType result = new ResultType();
   // Do Lots of stuff here.
   // update result

   return result;
}

I would like to create an async overload of this method, but don't want to duplicate all the code within it. So the method starts off simply:

public Task<ResultType> DoLotsOfStuffAsync(string p1, string p2)

The question becomes what do I do inside the new overload to call the original method?

I've seen several possible answers, but not sure if any of them are good ones, nor which is the best under what circumstances. So far, I've seen these:

Method 1: Use Task.Yield

public Task<ResultType> DoLotsOfStuffAsync(string p1, string p2)
{
   Task.Yield();
   return DoLotsOfStuff(p1, p2);
}

Method 2: Use Task.Run

public Task<ResultType> DoLotsOfStuffAsync(string p1, string p2)
{
   return await Task.Run(() => DoLotsOfStuff(p1, p2));
}

Method 3: Use Task.FromResult

public Task<ResultType> DoLotsOfStuffAsync(string p1, string p2)
{
   ResultType result = DoLotsOfStuff(p1, p2);
   return await Task.FromResult(result);
}

All three of those compile fine, so I'm not sure which to use. Are they equivalent? If not, what are the ramifications of using each?

As a bit of background, the libraries may be used in a variety of applications including ASP.Net Core web apps, .Net Core Console Apps, and possible .Net Core UI apps. I've done several hours of internet searching and found all of those methods, just nothing on which to use when.

Thanks!

Upvotes: 0

Views: 513

Answers (1)

Petrusion
Petrusion

Reputation: 1161

All three of those methods are fake asynchrony. If you are not going to provide an actually asynchronous implementation (by awaiting naturally/actually asynchronous operations like IO), then don't provide these overloads at all.

I highly recommend reading Task.Run Etiquette which Alexander Petrov already commented.

Upvotes: 1

Related Questions