It really depends on what your method does:
- no input / output, negligible amount of processor work.
- cpu intensive work
- intensive I / O
no I / O, negligible amount of processor work
You must calculate the result synchronously and create a task containing the result.
Task<Foo> ISomething.DoSomethingAsync() { Foo result; // do something not hurting performance // no I/O here return Task.FromResult(result); }
Note that when the method is called, any exception will be thrown, and not when the task is waiting. For the latter case, which corresponds to other types of work, you should use async, however:
async Task<Foo> ISomething.DoSomethingAsync() { Foo result; // do something not hurting performance // no I/O here return result; }
cpu intensive work
You must run the task with Task.Run and do the intensive work of the processor in the task.
Task<Foo> ISomething.DoSomethingAsync() { return Task.Run(() => { Foo result; // do some CPU intensive work here return result; }); }
intensive I / O
You must use the async and wait for some async input / output method. Do not use synchronous I / O methods.
async Task<Foo> ISomething.DoSomethingAsync() { Stream s = new .... // or any other async I/O operation var data = await s.ReadToEndAsync(); return new Foo(data); }
source share