Best way to convert callback based async method to expected task

What would be the best way to convert / migrate a “classic” asynchronous method that uses a callback for something that returns a (expected) task?

For example, given the following method:

public void GetStringFromUrl(string url, Action<string> onCompleted); 

The only way I know is to include this in the method returning the task:

 public Task<string> GetStringFromUrl(string url) { var t = new TaskCompletionSource<string>(); GetStringFromUrl(url, s => t.TrySetResult(s)); return t.Task; } 

Is this the only way to achieve this?

And is there a way to wrap the GetStringFromUrl (url, callback) call in the task itself (i.e. the call itself will be executed inside the task instead of synchronous)

+52
c # asynchronous task-parallel-library
Aug 09 2018-12-12T00:
source share
2 answers

Your code is short, readable, and efficient, so I don’t understand why you are looking for alternatives, but I can’t think of anything. I think your approach is reasonable.

I'm also not sure why you think the synchronous part is OK, but you want to avoid it in Task . If you think that the synchronous part may take too much time, correct it for both versions of the method.

But if you want to run it asynchronously (i.e. on ThreadPool ) only in the version of Task , you can use Task.Run() :

 public Task<string> GetStringFromUrl(string url) { return Task.Run(() => { var t = new TaskCompletionSource<string>(); GetStringFromUrl(url, s => t.TrySetResult(s)); return t.Task; }); } 
+26
Aug 09 2018-12-12T00:
source share

The intended implementation is perfect for this if the callback only ever handles successful situations. What happens if an exception occurs as part of the async subtexts of the GetStringFromUrl implementation? There is no real way for them to extend this to the Action callback ... do they just swallow it and return you zero or something else?

The only thing I would recommend is to use the following naming convention for such async methods with the suffix XXXAsync.

+3
Aug 09 '12 at 22:20
source share



All Articles