Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Net;
- using System.Threading;
- using System.Threading.Tasks;
- namespace ConsoleApp3
- {
- class Program
- {
- static void Main(string[] args)
- {
- CancellationTokenSource cts = new CancellationTokenSource();
- Call(cts.Token);
- for (int i = 0; i < 1000; i++)
- {
- Thread.Sleep(20);
- if (i == 30)
- cts.Cancel();
- Console.WriteLine($"Do something else({i})");
- }
- Console.ReadLine();
- }
- static async void Call(CancellationToken cancellationToken)
- {
- try
- {
- Downloader downloader = new Downloader();
- string res = await downloader.DownloadAsync("https://pokeapi.co/api/v2/pokemon/1/", cancellationToken);
- Console.WriteLine($"RESPONCE: {res}");
- }
- catch (OperationCanceledException)
- {
- Console.WriteLine($"ERROR");
- }
- }
- }
- class Downloader
- {
- public Task<string> DownloadAsync(string url, CancellationToken cancellationToken)
- {
- TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();
- using (var client = new WebClient())
- {
- Uri Uri = new Uri(url);
- cancellationToken.Register(() => client.CancelAsync());
- client.DownloadStringCompleted += (object sender, DownloadStringCompletedEventArgs e) =>
- {
- if (e.Cancelled)
- {
- try
- {
- cancellationToken.ThrowIfCancellationRequested();
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message + "xui" + e.Error.Message);
- tcs.SetCanceled();
- return;
- }
- }
- //if (e.Error != null)
- //{
- // Console.WriteLine("Can't set result" + e.Error.Message);
- // return;
- //}
- tcs.SetResult(e.Result);
- };
- client.DownloadStringAsync(Uri, cancellationToken);
- }
- return tcs.Task;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement