3

I tried to use the following code to run some task in thread pool:

private async void button1_Click(object sender, EventArgs e)
{
   await test().ConfigureAwait(continueOnCapturedContext: false);
}
private Task test()
{
   Thread.Sleep(100000);
   return null;
}

The code is supposed to run in the threadpool, however the current UI thread is still being blocked.

So can anyone help to take a look? thanks,

HPPPY
  • 39
  • 1
  • 3
  • 5
    Using `async` / `await` does not mean that your task will run on a different thread. – dotnetom Apr 12 '16 at 04:12
  • 1
    but should "continueOnCapturedContext: false" make it run in thread pool? – HPPPY Apr 12 '16 at 04:16
  • No, `continueOnCapturedContext: false` will ensure that the continuation of an `await` is not invoked using the `SynchronizationContext` and instead finishes in `ThreadPool`. In your question your `Thread.Sleep()` is simply executed on the same thread that invoked the `test()` method, therefore it blocks. The code will run synchronously until it comes to the first `await`. So `test()` is invoked synchronously, the result (a `null` `Task`) is "awaited". – deloreyk Apr 12 '16 at 05:02
  • Is your Test() method is `synchronized` or do it have `async` invocation ? – Eldho Apr 12 '16 at 05:57
  • if its synchronized you could try using `await Task.Run(() =>Test());` – Eldho Apr 12 '16 at 05:59
  • http://stackoverflow.com/a/18015586/1876572 – Eldho Apr 12 '16 at 06:03
  • Your code is returning `null` instead of a `Task` that represents the asynchronous operation! – David Pine Apr 12 '16 at 12:06

2 Answers2

5

The code is supposed to run in the threadpool

No, that is not at all true. async does not run your code on a thread pool thread.

I suggest you read my async intro, which explains what async does do, and the official async FAQ, which addresses the thread pool misconception specifically:

Does the “async” keyword cause the invocation of a method to queue to the ThreadPool? To create a new thread? To launch a rocket ship to Mars?

No. No. And no.

Community
  • 1
  • 1
Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810
2

You should use Task.Delay method.

private async void button1_Click(object sender, EventArgs e)
{
   await test();
}

private Task test()
{
    return Task.Delay(100000);
}

Edit :

Related question / answer.

Community
  • 1
  • 1
Fabien ESCOFFIER
  • 4,751
  • 1
  • 20
  • 32