1

(based on my other question here)

I have created the following async web-api-controller action, but it never returns

public async Task<string> Tester()
{
    Task t = new Task(() => Thread.Sleep(2000));

    await t;

    return "OK";
}

what am I doing incorrectly?

Community
  • 1
  • 1
Elad Katz
  • 7,483
  • 5
  • 35
  • 66

2 Answers2

9

It never returns because the task was never started, so it hangs. Call the Task.Start method:

Task t = new Task(() => Thread.Sleep(2000));
t.Start();

Or use Task.Run instead:

Task t = Task.Run(() => Thread.Sleep(2000));

Or use Task.Delay instead which is non-blocking (unless you used Thread.Sleep just for the sake of an example):

Task t = Task.Delay(2000);

Bear in mind that in a web application, everything except I/O-bound work should be synchronous. Deferring CPU-bound work to the thread pool won't buy you anything - if anything, it'll hurt performance.

See Stephen Cleary's Task.Run Etiquette Examples: Don't Use Task.Run in the Implementation

dcastro
  • 66,540
  • 21
  • 145
  • 155
  • @EladKatz Yes, it is. DB access often benefits from being async. – dcastro Nov 05 '14 at 08:43
  • I'm using fiddler to run it 10 times simultaneously, yet it returns after 2,4,6,,20 seconds respectively. why? why is it still sequential? – Elad Katz Nov 05 '14 at 08:55
  • @EladKatz you don't need async to be able to handle multiple requests simultaneously. If your requests are being handled sequentially, then your issue lies somewhere else. Seems like a config issue, maybe on IIS or Web.config, I dunno, I've never seen that. – dcastro Nov 05 '14 at 11:30
1

I tried it in console application and it worked!

What you only need to do is to start the task t:

static void Main(string[] args)
    {
        string test = Tester().Result;
        Console.WriteLine(test);
    }

    public static async Task<string> Tester()
    {
        Task t = new Task(() => System.Threading.Thread.Sleep(2000));
        t.Start();
        await t;

        return "OK";
    }
Onel Sarmiento
  • 1,608
  • 3
  • 20
  • 46