TheWommies
TheWommies

Reputation: 5072

TaskCompletionSource to represent Async

Sorry my knowledge with threads is still a bit weak.

Just reading around. If you use TaskCompletionSource to represent some IO Async operation.

Like say some DownloadAsync, you are not tying up a thread as I understand?

I always thought when something is happening asynchronously it must be tying up a thread?

Any clarification is appreciated.

Thanks

Upvotes: 1

Views: 521

Answers (1)

Arjun
Arjun

Reputation: 268

The DownloadFileAsync of the webclient provides a good opportunity to apply TPL in a Event based asynchronous model. Since the action that includes the call to the DownloadFileAsync completes quickly, the real work isn't done until the DownloadFileCompleted event is triggered. This is where the TaskCompletionSource comes into play.

   var downloadCompletionSource = new TaskCompletionSource<bool>();
  webClient.DownloadFileCompleted+=
                (s, e) =>
                    {
                         if (e.Error != null)
                           {
                                downloadCompletionSource.SetException(e.Error);
                            }
                            else
                            {
                                downloadCompletionSource.SetResult(true);
                            }
                        }

                    };

          webClient.DownloadFileAsync(new Uri(downloadUrl), destinationFilePath);

            try
            {
                downloadCompletionSource.Task.Wait();

            }
            catch (AggregateException e)
            {

            }

More can be found here in MSDN

Upvotes: 1

Related Questions