SF Developer
SF Developer

Reputation: 5384

Task<class> calling a non async method

I have a 3rd party DLL that I cannot change and I wanted to make asynchronous one of its method.
So I have:

procedure bool Food()
{
   Task<ReturnClass> response = SomeDLL.SyncMethod(); // Method returns "ReturnClass"

   response.ContinueWith (_ => 
   {
     return response.Result != null;
   });
 }

I get the known compile error:
Cannot implicitly convert type 'SomeDLL.ReturnClass' to 'System.Threading.Tasks.Task'

It's important to notice that I cannot change the 3rd PartyDLL

  1. What's the right way to accomplish this goal?
    I need to wait for the SomeDLL SyncMethod return so that's why I used ContinueWith.

  2. Does the procedure bool Foo need to set as "async"?

Upvotes: 0

Views: 658

Answers (1)

svick
svick

Reputation: 244777

You say you want to make the method async, but you don't say why. If you're looking to gain the scalability improvements of async, then that's not possible: SyncMethod() will block a thread and there's nothing you can do about that.

If you're in a UI application and you want gain better responsiveness, then you can do that by invoking your method on a background thread using Task.Run(). Something like:

async Task<bool> FoodAsync()
{
   Task<ReturnClass> response = Task.Run(() => SomeDLL.SyncMethod());

   return await response != null;
}

This assumes you're using C# 5. If that's not the case, you can still do this, but the code is going to be more complicated:

Task<bool> FoodAsync()
{
   Task<ReturnClass> response =
       Task.Factory.StartNew(() => SomeDLL.SyncMethod());

   return response.ContinueWith(_ => response.Result != null);
}

Upvotes: 2

Related Questions