There are already two good answers, but add my 0.02 ...
If you are talking about using asynchronous operations, async
/ await
works great for both I / O binding and CPU binding.
I think that MSDN documents have a slight bias towards creating asynchronous operations, in which case you want to use TaskCompletionSource
(or similar) for I / O-bound and Task.Run
(or similar) for CPU-related. Having created the original Task
shell, it is best used by async
and await
.
In your specific example, this really comes down to how long LoadHtmlDocument
takes. If you delete Task.Run
, you will execute it in the same context that calls LoadPage
(possibly in the user interface thread). The Windows 8 manuals indicate that any operation that takes more than 50 ms should be done async
... given that 50 ms on your development machine may be longer on the client machine ...
So, if you can guarantee that LoadHtmlDocument
will run for less than 50 ms, you can simply execute it directly:
public async Task<HtmlDocument> LoadPage(Uri address) { using (var httpResponse = await new HttpClient().GetAsync(address))
However, I would recommend ConfigureAwait
as @svick said:
public async Task<HtmlDocument> LoadPage(Uri address) { using (var httpResponse = await new HttpClient().GetAsync(address) .ConfigureAwait(continueOnCapturedContext: false))
With ConfigureAwait
, if the HTTP request does not complete immediately (synchronously), then this (in this case) will cause LoadHtmlDocument
be executed in the thread pool thread without explicitly calling Task.Run
.
If you are interested in async
performance at this level, you should check out the Stephen Toub video and MSDN article on this subject. He has a lot of useful information.
Stephen Cleary Feb 15 '13 at 20:20 2013-02-15 20:20
source share