Пример #1
0
        // 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);
        }
        public IAsyncResult BeginDownloadAndSave(AsyncCallback callback, object userState)
        {
            var localState = new State(userState);

            _downloadFromInternet1.BeginDownload(Download1Callback, localState);
            _downloadFromInternet2.BeginDownload(Download2Callback, localState);
            return(localState.TaskCompletionSource.Task);
        }