I'm working on a class which has a method with Action<T>
parameter:
public void RegisterCallback<T> (Action<T> callback);
This works good enough.
instance.RegisterCallback<string>(Callback); //method group
instance.RegisterCallback<string>(t => {}); //lambda
Now I want to create an overload for this method which accepts async
method. So that I can use it with task returning callbacks and treat them in a different way.
instance.RegisterCallback<string>(AsyncCallback); //method group with async
Where AsyncCallback
is
private Task AsyncCallback(string s)
{
return Task.Delay(0);
}
The naive approach was to have a method like this one:
void RegisterCallback<T>(Func<T, Type> callback);
It has some problems though:
//1
instance.RegisterCallback<string>(async t => await Task.Delay(0));
//2
instance.RegisterCallback<string>(AsyncCallback); //method group with async
the first one gets resolved to Action<T> callback
overload and the second fails to compile because of ambiguous invocation.
Well, that makes sense and I'm ok about this interface:
void RegisterAsyncCallback<T>(Func<T, Task> callback);
However these two calls are compiled with no problems:
instance.RegisterCallback<string>(async t => await Task.Delay(0));
instance.RegisterAsyncCallback<string>(async t => await Task.Delay(0));
Is there a way to design this public api so that a user will only use void
callbacks with one method and task returning with another.
Perhaps someone can point me to the existing api where similar problem was solved?
The full code can be found here.