Calling an async method using a Task.Run seems wrong?

前端 未结 2 1877
野趣味
野趣味 2020-12-10 13:29

I recently came across this code written by a contractor we had working for us. It\'s either devilishly clever or silly (I think the latter but I wanted a second opinion). I

2条回答
  •  执笔经年
    2020-12-10 14:07

    I'm also not convinced this is really an async method because it will still wait, right?

    It isn't, as Yuval explained. You shouldn't use sync over async.

    Now as I understand it that first Task.Run() is pointless and inefficient?

    Not really, there is value in using Task.Run in such a way.

    Since you're blocking on an async method (which you shouldn't do) there is a chance you'll deadlock. That happens in UI apps and asp.net where you have a SynchronizationContext.

    Using Task.Run clears that SynchronizationContext since it offloads the work to a ThreadPool thread and removes the risk for a deadlock.

    So, blocking is bad, but if you end up doing it using Task.Run is safer.

提交回复
热议问题