Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Await async TaskEx

What is TaskEx? In http://www.i-programmer.info/programming/c/1514-async-await-and-the-ui-problem.html?start=1 or await TaskEx.Delay or Await async clarification. I use

Task DoWork()
{
    return Task.Run(() =>
    {
        for (int i = 0; i < 30; i++)
        {
            Thread.Sleep(1000 * 60 * 30);
        }
    });
}

Examples use this

Task DoWork()
{
   return TaskEx.Run(() =>
   {
     for (int i = 0; i < 10; i++)
     {
         Thread.Sleep(500);
     }
   }
 });

I call it like await DoWork(); If you use just Task, await returns nothing and there is no response. If I use TaskEx it says it doesn't exist in context. Should TaskEx be a class or something with some sort of function? Fists one Works it's my mistake.

like image 315
Vladimir Laktionov Avatar asked Jan 27 '16 15:01

Vladimir Laktionov


People also ask

Can we use async without await C#?

The warning is exactly right: if you mark your method async but don't use await anywhere, then your method won't be asynchronous. If you call it, all the code inside the method will execute synchronously.

When should I use async await C#?

The async keyword turns a method into an async method, which allows you to use the await keyword in its body. When the await keyword is applied, it suspends the calling method and yields control back to its caller until the awaited task is complete. await can only be used inside an async method.

Does await Block C#?

When the await operator is applied to the operand that represents an already completed operation, it returns the result of the operation immediately without suspension of the enclosing method. The await operator doesn't block the thread that evaluates the async method.

What is await Task run C#?

The async/await approach in C# is great in part because it isolates the asynchronous concept of waiting from other details. So when you await a predefined method in a third-party library or in . NET itself, you don't necessarily have to concern yourself with the nature of the operation you're awaiting.


1 Answers

TaskEx was just an extra class which initially shipped with the CTPs of the async/await extensions for C# 5 before .NET 4.5 shipped... and is now part of the Async Targeting Pack (aka the Microsoft.Bcl.Async NuGet package) in case you want to use async/await but are targeting .NET 4.0 (which doesn't have some of the code required for it).

If you're using .NET 4.5 or later, just use Task.Run, which does the same thing. (You won't be using the targeting pack, so you won't have TaskEx.) The async targeting pack can't add a static method to the existing Task class, hence the need for TaskEx existing at all.

like image 86
Jon Skeet Avatar answered Sep 24 '22 13:09

Jon Skeet