It looks like Implementing an interface that requires a return type of task in synchronous code , although I'm curious if I should just ignore the compiler error generated instead.
Say I have an interface like this:
public interface IAmAwesome { Task MakeAwesomeAsync(); }
In some implementations that create huge benefits from asynchronous use with asyncand await. This is really what the interface is trying to do.
async
await
In other cases, perhaps rare, only a simple synchronous method is needed to create a terrific method. Therefore, suppose the implementation is as follows:
public class SimplyAwesome : IAmAwesome { public async Task MakeAwesomeAsync() { // Some really awesome stuff here... } }
This works, but the compiler warns:
"" . await API, " TaskEx.Run(...)", .
:
public class SimplyAwesome : IAmAwesome { public async Task MakeAwesomeAsync() { await Task.Run(() => { // Some really awesome stuff here, but on a BACKGROUND THREAD! WOW! }); } }
: , ? , , , .
, , async , , . , , , , , , . - , .
, , async Task.FromResult . ( ), , . , Task, , async .
Task.FromResult
Task
, ? , .
" Task.Run ". , async, async , .
. , . , , . , , .
. "Awesome" :
public interface MakeAwesomeAsync { Task MakeAwesomeAsync(); } public interface MakeAwesome { void MakeAwesome(); }
. , Task Task.FromResult. , , .
, 3 , :
public class SimplyAwesome : IAmAwesome { public Task MakeAwesomeAsync() { // run synchronously return TaskExtensions.CompletedTask; } }
while(false){}
Servy , . , , .
, async (.. await MakeAwesomeAsync()), , , async .
await MakeAwesomeAsync()
-, .Net Framework. . , , Task.Delay, , , await :
Task.Delay
try { Task.Delay(-2); } catch (Exception e) { Console.WriteLine(e); }
.Net .Net, , , .