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?

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

@EladKatz Yes, it is. DB access often benefits from being async.
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?
@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.
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";
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.