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) 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 快得多。