Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to declare Interface " async Task<myObject> MyMethod(Object myObj); " [duplicate]

I'm unable to declare

interface IMyInterface
{
   async Task<myObject> MyMethod(Object myObj);
}

The compiler tells me:

  • The modifier async isn't valid for this item
  • The async modifier can only be used for methods that have a body

Is this something that should be implemented, or does the nature of async & await prohibit this from ever occurring?

like image 957
makerofthings7 Avatar asked Oct 24 '12 12:10

makerofthings7


3 Answers

Whether a method is implemented using async/await or not is an implementation detail. How the method should behave is a contract detail, which should be specified in the normal way.

Note that if you make the method return a Task or a Task<T>, it's more obvious that it's meant to be asynchronous, and will probably be hard to implement without being asynchronous.

From https://stackoverflow.com/a/6274601/4384

like image 80
stuartd Avatar answered Nov 15 '22 01:11

stuartd


Whether or not your implementation is async, has no relevance to your interface. In other words, the interface cannot specify that a given method must be implemented in an asynchronous way.

Just take async out of your interface and it will compile; however, there is no way to enforce asynchronous implementation just by specifying an interface.

like image 24
Roy Dictus Avatar answered Nov 15 '22 00:11

Roy Dictus


If you have an interface with two implementations (one that is truly async and the other that is synchronous) this is what it would look like for each implementation - with both returning a Task<bool>.

public interface IUserManager
{
    Task<bool> IsUserInRole(string roleName);
}

public class UserManager1 : IUserManager
{
    public async Task<bool> IsUserInRole(string roleName)
    {
        return await _userManager.IsInRoleAsync(_profile.Id, roleName);
    }
}

public class UserManager2 : IUserManager
{
    public Task<bool> IsUserInRole(string roleName)
    {
        return Task.FromResult(Roles.IsUserInRole(roleName));
    }
}

If it is a void method you need to return Task.CompletedTask; from the non async method (I think .NET 4.5 and later)

See also : Return Task<bool> instantly

like image 7
Simon_Weaver Avatar answered Nov 14 '22 23:11

Simon_Weaver