C # blocking code in an asynchronous method

Im using the MvvmCross and AsyncEx library in a Windows 10 application (UWP).

In ViewModel, I have an INotifyTaskCompletion (1) property that is connected to the Async method in ViewModel (2)

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

  • Checks local cache
  • Download data asynchronously
  • Adds data to the cache

Caching code cannot be made asynchronous, so the library method contains both blocking and asynchronous code.

Q. What is the best way to prevent user interface thread blocking?

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

Move caching calls to (2), for example.

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

Is there a better way?

+5
source share
1 answer

If you have completely synchronous code that you cannot change to return while waiting and want to make it asynchronous, then yes, your only choice if you want to use async/await is to use Task.Run() .

Sort of:

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

It should be good.

+3
source

Source: https://habr.com/ru/post/1245469/


All Articles