56319

Convert Action callback to an await

Question:

I have a method that takes a Action<String>. When the method finishes its processing it calls the Action<String> with the return value.

MethodWithCallback((finalResponse)=> { Console.WriteLine(finalResponse); });

I want to use this in a web.api async controller. How do I wrap this method so I can await for this method to complete in an async manner. I cannot modify the method itself, it is in a legacy code base.

What I would like to be able to do is this

String returnValue = await MyWrapperMethodThatCallsMethodWithCallback();

Answer1:

You can leverage the <a href="http://msdn.microsoft.com/en-us/library/dd449174.aspx" rel="nofollow">TaskCompletionSource</a> class and solve the problem in a generic way:

Task<T> AsAsync<T>(Action<Action<T>> target) { var tcs = new TaskCompletionSource<T>(); try { target(t => tcs.SetResult(t)); } catch (Exception ex) { tcs.SetException(ex); } return tcs.Task; }

That way you don't have to modify your MethodWhitCallback:

var result = await AsAsync<string>(MethodWithCallback); Console.WriteLine(result);

Recommend

  • Newtonsoft inline formatting for subelement while serializing
  • Why is RAM in powers of 2?
  • Visual basic auto imports namespaces
  • C# where to add a method
  • WPF Listbox commands
  • How to fallback to entirely different index page if user has javascript disable?
  • Best HTML5 structure for a layout where the title/header is outside the article tag
  • How to make SASS put relative paths in its output
  • VB.NET 2012 Property Set on Property Get
  • is there a way to update filter with async data
  • Authentication failed with Azure Active Directory in Windows Phone
  • Magento get URL before current
  • In loopback documentation what does variable 'cb' stands for?
  • Retrieve IP address of device
  • Prevent Tomcat from caching request during starup
  • How to autopopulate a field in SugarCRM form
  • ThreadStatic in asynchronous ASP.NET Web API
  • How do I signal completion of my dataflow?
  • Conversion from string “a” to type 'Boolean' is not valid
  • How to use JavaScript to determine whether a file exists in a directory?
  • OOP Javascript - Is “get property” method necessary?
  • How can I sort a a table with VBA with given text condition?
  • How to attach a node.js readable stream to a Sendgrid email?
  • Sencha Touch 2.0 Controller refs attribute not working?
  • Reading JSON from a file using C++ REST SDK (Casablanca)
  • FB SDK and cURL: Unknown SSL protocol error in connection to graph.facebook.com:443
  • Master page gives error
  • Can a Chrome extension content script make an jQuery AJAX request for an html file that is itself a
  • Redux, normalised entities and lodash merge
  • Hazelcast - OperationTimeoutException
  • Upload files with Ajax and Jquery
  • How to pass list parameters for each object using Spring MVC?
  • RestKit - RKRequestDelegate does not exist
  • Is there a mandatory requirement to switch app.yaml?
  • bootstrap to use multiple ng-app
  • Revoking OAuth Access Token Results in 404 Not Found
  • Proper way to use connect-multiparty with express.js?
  • Binding checkboxes to object values in AngularJs
  • UserPrincipal.Current returns apppool on IIS
  • How to load view controller without button in storyboard?