C# httpclient GetAsync()

using System.Diagnostics;

namespace ConsoleApp15
{
    internal class Program
    {
        static CancellationTokenSource cts { get; set; }
        static int idx = 0;
        static Stopwatch watch { get; set; } 
        
        static async Task Main(string[] args)
        {
            cts = new CancellationTokenSource();
            watch = new Stopwatch();
            watch.Start();

            Task.Run(() =>
            {
                while (!cts.IsCancellationRequested)
                {
                    Console.WriteLine($"{++idx},{DateTime.UtcNow.ToString("yyyyMMddHHmmssffff")},time cost:{watch.ElapsedMilliseconds} mills!");
                    Thread.Sleep(1000);
                }
            }, cts.Token);
            await DownloadViaHttpClient();
        }

        private static async Task DownloadViaHttpClient()
        {
            string url = "https://download.visualstudio.microsoft.com/download/pr/7212fb94-d2c2-4a7d-9fbb-eecb1b9d9c78/f7f31cf72ebb4188a993c1f09d9a0827/dotnet-sdk-8.0.307-win-x64.exe";
            using (HttpClient client = new HttpClient())
            {
                string fileName = System.IO.Path.GetFileName(url);
                using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.Write, 4096, true))
                {
                    var httpResponseMsg = await client.GetAsync(url);
                    httpResponseMsg.EnsureSuccessStatusCode();
                    var downloadedStream = await httpResponseMsg.Content.ReadAsStreamAsync();
                    downloadedStream.CopyTo(fs);
                    cts.Cancel();
                    watch.Stop();
                    Console.WriteLine($"Done! filename:{fileName},time cost:{watch.ElapsedMilliseconds} mills!");
                }
            }
        }
    }
}

 

来源链接:https://www.cnblogs.com/Fred1987/p/18666395

请登录后发表评论

    没有回复内容