Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# blocking code in async method

I’m using MvvmCross and the AsyncEx library within a Windows 10 (UWP) App.

In a ViewModel, I have an INotifyTaskCompletion property (1) which is wired-up to an Async method in the ViewModel (2)

In (2), I call an Async library method which:

  • Checks a local cache
  • Downloads data asynchronously
  • Adds the data to the cache

The caching code cannot be made asynchronous and so the library method contains both blocking and asynchronous code.

Q. What’s the best way to prevent blocking the UI thread?

I understand from Stephen Cleary to not to block in asynchronous code and not use Task.Run in library methods. So do I have to….

Move the caching calls into (2) e.g.

  • Use Task.Run (to check the cache)
  • Call the library method asynchronously
  • Use Task.Run again (to cache the data)?

Is there a better way?

like image 713
Howard Avatar asked Mar 21 '16 09:03

Howard


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr. Stroustroupe.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

What is C language basics?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.


1 Answers

If you have completely synchronous code which you can't change to make it return an awaitable, and want to make it asynchronous, then yes, your only choice if you want to use async/await is to use Task.Run().

Something like:

public async Task<T> MyMethod()
{
   T result = await Task.Run(() => CheckCacheOnSyncMethodICantChange());
   if(result != null)
   {
     result = await MyLibraryMethodThatReturnsATask();
     await Task.Run(() => AddToCacheOnSyncMethodICantChange(result));
   }
   return result;
}

Should be ok.

like image 129
Jcl Avatar answered Oct 03 '22 08:10

Jcl