Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use async on an empty interface method

Say I have an interface

interface IFoo {
    Task SomeMethodAsync();
}

And I wanted to implement this interface, but for one class the method is blank.

Should I live with the warning this produces?

async Task SomeMethodAsync() {}

Or should I have it return some dummy task?

async Task SomeMethodAsync() { await Task.Run(() => {}); }

Or is there another option?

Also I want to implement this method as an explicit interface method. Will that make any difference?

like image 916
Cameron MacFarland Avatar asked Aug 28 '12 11:08

Cameron MacFarland


3 Answers

I ran into this with an abstract base class. I tried Stephen Cleary's method, but was getting compiler errors in C# 6.

An example of my base method:

protected abstract Task OnFoo(Bar bar);

This is what I had to do in my derived class:

protected override async Task OnFoo(Bar bar)
{
    await Task.FromResult(true);
}

The problem with the other answer was the return keyword in the phrase. Because the return value of Task is essentially void, you can't return anything. Also, the await keyword is required.

like image 127
krillgar Avatar answered Sep 25 '22 01:09

krillgar


Methods that return Task do not have to be async.

I would recommend something like this:

Task IFoo.SomeMethodAsync()
{
  return Task.FromResult(true);
}

I'm assuming that if this was a synchronous method, you would just have an empty method body; this is the async equivalent of an empty method body.

like image 15
Stephen Cleary Avatar answered Oct 19 '22 07:10

Stephen Cleary


It depends only how do you decide that framework has to handle such cases.

You have, imo, several options :

  • raise an exception (will break immidiately execution, and you have to handle it in some way in some place in execution chain).

  • return default-value (that can be a solution offered by you: just an empty task that doesn't do anything. Bad about this is that I call function expecting it does something, it doesn't notify me about anything but do not do anything either. Imo, this is bad design.

  • return some not-valid-value, which intercepted by caller so caller "knows" that something is not ok.

like image 2
Tigran Avatar answered Oct 19 '22 06:10

Tigran