小编wes*_*est的帖子

Task.Delay 与 Thread.Sleep 的区别

private static async Task MainFunc()
{
    var watch = System.Diagnostics.Stopwatch.StartNew();

    List<Task<int>> list = new List<Task<int>>();

    for (int i = 1; i <= 3; i++)
    {
        list.Add(TaskFunc(i));
    }

    var taskResult = await Task.WhenAll(list);

    foreach (var item in taskResult)
    {
        Console.Write($"i= {item}.{ Environment.NewLine }");
    }

    list.Clear();

    watch.Stop();
    var elapsedMs1 = watch.ElapsedMilliseconds;

    Console.WriteLine($"Total execution time: { elapsedMs1 }");
    Console.WriteLine();


    watch.Restart();


    for (int i = 1; i <= 3; i++)
    {
        list.Add(Task.Run(() => ThreadFunc(i)));
    }

    var threadResult = await Task.WhenAll(list);

    foreach (var item in …
Run Code Online (Sandbox Code Playgroud)

c# multithreading task async-await

5
推荐指数
1
解决办法
87
查看次数

HttpResponseMessage.Content.ReadAsStreamAsync() 与 HttpResponseMessage.Content.ReadAsStringAsync()

var request = new HttpRequestMessage(HttpMethod.Get, $"api/Items");
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

using (var response = await _httpClient.SendAsync(request))
{
   response.EnsureSuccessStatusCode();
   var stream = await response.Content.ReadAsStreamAsync();        

     using (var streamReader = new StreamReader(stream))
     {
       using (var jsonTextReader = new JsonTextReader(streamReader))
       {
         var jsonSerializer = new JsonSerializer();
         var data =  jsonSerializer.Deserialize<Item>(jsonTextReader);
       }
     }
}
Run Code Online (Sandbox Code Playgroud)

...

var request = new HttpRequestMessage(HttpMethod.Get, "api/Items");
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await _httpClient.SendAsync(request);

response.EnsureSuccessStatusCode();

var content = await response.Content.ReadAsStringAsync();
var data = JsonConvert.DeserializeObject<List<Item>>(content);
Run Code Online (Sandbox Code Playgroud)

我已经运行了这两个示例,我很好奇它们总是得到相同结果的区别是什么,ReadAsStreamAsync 比 ReadAsStringAsync 快得多。

c# asp.net api stream asp.net-core

5
推荐指数
2
解决办法
3387
查看次数

标签 统计

c# ×2

api ×1

asp.net ×1

asp.net-core ×1

async-await ×1

multithreading ×1

stream ×1

task ×1