Synchronous implementation of an interface that returns a task

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.

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!
        });
    }
}

: , ? , , , .

+4
3

, , async , , . , , , , , , . - , .

, , async Task.FromResult . ( ), , . , Task, , async .

+10

, ? , .

" Task.Run ". , async, async , .

:

. , . , , . , , .

. "Awesome" :

public interface MakeAwesomeAsync
{
    Task MakeAwesomeAsync();
}

public interface MakeAwesome
{
    void MakeAwesome();
}

. , Task Task.FromResult. , , .

+6

, 3 , :

  • async
  • / async
  • async .

:

public class SimplyAwesome : IAmAwesome 
{
    public Task MakeAwesomeAsync() 
    {
        // run synchronously
        return TaskExtensions.CompletedTask;
    }
}

:

  • async (, inlining) - try-catch, .
  • , , , await.
  • - async. while(false){} , , .

Servy , . , , .

, async (.. await MakeAwesomeAsync()), , , async .

-, .Net Framework. . , , Task.Delay, , , await :

try
{
    Task.Delay(-2);
}
catch (Exception e)
{
    Console.WriteLine(e);
}

.Net .Net, , , .

+4
source

All Articles