Posts

Showing posts with the label C#

Calling Long Running Methods Asynchronously

Image
When you are able to call an async method, do it using async and await or by making your method return a Task: p ublic async Task < string > RequestData ( Uri uri ) {     WebClient webClient = new WebClient ();     return await webClient.DownloadStringTaskAsync ( uri ); } // Rely on underlying Tasks whenever possible. public Task < string > RequestDataAsync ( Uri uri ) {     WebClient webClient = new WebClient ();     return webClient.DownloadStringTaskAsync ( uri ); } // Rely on underlying Tasks whenever possible. Dealing with synchronous calls When the method you are calling is not asynchronous, wrap the method in a task delegate:   public Task < string > RequestDataAsync ( Uri uri ) {     return Task .Run < string >(         () =>         {             WebClient webClient = new WebClient ();             return webClient.DownloadString ( uri );         }); } // Create Tasks when you have no