Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

(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?

share|improve this question

2 Answers 2

up vote 7 down vote accepted

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

share|improve this answer
    
db access is i/o bound work right? –  Elad Katz Nov 5 '14 at 8:42
    
@EladKatz Yes, it is. DB access often benefits from being async. –  dcastro Nov 5 '14 at 8: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 5 '14 at 8: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 5 '14 at 11:30

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";
    }
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.