0

I know there are answers to this, but none of them are crystal clear. Is there any difference between the following?

// Option A
var result = Task.Run(() => GetAsync(id)).GetAwaiter().GetResult();

// Option B
var result = Task.Run(async () => await GetAsync(id)).GetAwaiter().GetResult();

Is one of these better or preferred?

To clarify, the reason Task.Run() is used is that this is called from a synchronous method, one that cannot be made async. The reason it cannot be made async is that it is called from a razor view, which (in ASP.NET 4.5) is sync only. The reason Task.Run() is used is to be certain we don't get deadlocks.

EDIT This is not a duplicate of the linked question

Marius
  • 57,995
  • 32
  • 132
  • 151
  • When you use Task.Run, you explicitly use a thread-pool thread to execute your delegate. If you mark a method with the async keyword, but don't await anything internally, it will execute synchronously. – Vivek Nuna Oct 13 '16 at 13:56
  • 1
    @Marius: This is a duplicate, it's just not obvious. When you write a lambda expression, the compiler will generate a method for you. Your generated method for "Option A" looks like `Task _lambda(id) { return GetAsync(id); }` and the generated method for "Option B" looks like `async Task _lambda(id) { return await GetAsync(id); }`, and the difference between those is covered in the duplicated question. – Stephen Cleary Oct 13 '16 at 16:49

0 Answers0