2

Here's a C# async function Foo() in which a blocking function (File.WriteAllText) is to be called.

async Task Foo()
{
    File.WriteAllText(...);
}

If Foo is called by main UI thread, using Task.Run() for calling the blocking function prevents main UI thread from blocking so that UX runs fluently.

async Task Foo()
{
    await Task.Run(async ()=> { File.WriteAllText(...); }).ConfigureAwait(false);
}

Question:

If Foo is called by non-UI thread(e.g. worker threads), as worker threads don't interfere with UX fluency, calling the blocking function directly is of no problem, I think.

Is my thought right? Is there any other problem I don't know yet?

Hyunjik Bae
  • 2,721
  • 2
  • 22
  • 32
  • 3
    I think you are right. As long as it is not the UI thread, you have nothing to worry about. – trinalbadger587 Aug 03 '21 at 01:54
  • 1
    It does have the downside of hogging a threadpool thread, and it also doesn't work in single-threaded environments. You are best off using `WriteAllTextAsync ` instead – Charlieface Aug 03 '21 at 02:28
  • Sorry, I edited my question. I forgot to add 'await' statement. – Hyunjik Bae Aug 03 '21 at 02:33
  • Yes you are right. Badly behaved code is going to block SOME thread no matter what. If you absolutely must call it, it should be on a worker thread. If you're already on a worker thread when calling it there's no reason to wrap it in a new Task.Run as long as you're willing to accept that your calling thread will be blocked. But obviously if you have a well behaved async API available instead it's better to use that always. – Emperor Eto Aug 03 '21 at 02:50
  • As a side note, the first `Foo` implementation most probably generates a [CS1998](https://stackoverflow.com/questions/29923215/should-i-worry-about-this-async-method-lacks-await-operators-and-will-run-syn) warning about an `async` method that lacks an `await` operator, a warning that you shouldn't ignore, and the second `Foo` implementation violates [Microsoft's guidelines](https://devblogs.microsoft.com/pfxteam/should-i-expose-asynchronous-wrappers-for-synchronous-methods/ "Should I expose asynchronous wrappers for synchronous methods?") regarding the use of the `Task.Run` method. – Theodor Zoulias Aug 03 '21 at 03:07

0 Answers0