How can I wrap a method with a callback parameter

2019-02-18 21:02发布

问题:

I have a Silverlight 5 application with a bunch of methods having a signature similar to this:

public void AskConfirmation(Action<bool> callback);

Typically these methods raise an InteractionRequest to interact with the user, waiting for input.

I'd like to leverage the Task Parallel Library and the async/await keywords, and so I want to define a second method with the following signature :

public Task<bool> AskConfirmation();

And this second method would rely on the first one. Unfortunately I just couldn't figure out how to implement it.

Wrapping asynchronous operations into Tasks is easy when they follow the Event-based Asynchronous pattern or the Begin/End pattern, but these were clear overkills in my case so I didn't want to implement them. But now I'm stuck. Did anybody ever faced the same problem and found a solution for it ?

回答1:

public Task<bool> AskConfirmation()
{
    var tcs = new TaskCompletionSource<bool>();
    AskConfirmation(b => tcs.TrySetResult(b));
    return tcs.Task;
}