// Very old-school implementations use an IAsyncResult by Jeffrey Richter from an old MSDN article: // https://docs.microsoft.com/en-us/archive/msdn-magazine/2007/march/implementing-the-clr-asynchronous-programming-model // This example code uses the much simpler Task/TaskCompletionSource approach introduced in .NET 4.0. public IAsyncResult BeginDownloadAndSave(AsyncCallback callback, object state) { var tcs = new TaskCompletionSource <object>(state); _downloadFromInternet.BeginDownload(ar => { string data; try { data = _downloadFromInternet.EndDownload(ar); } catch (Exception exception) { tcs.TrySetException(exception); return; } _saveToDatabase.BeginSave(data, ar => { try { _saveToDatabase.EndSave(ar); } catch (Exception exception) { tcs.TrySetException(exception); return; } tcs.TrySetResult(null); }, null); }, null); return(tcs.Task); }
private void SaveResults(State state) { _saveToDatabase.BeginSave(state.Data1 + state.Data2, SaveCallback, state); }