如果我触发多个异步 Web 请求,将结果附加到全局变量是否安全,例如StringBuilder
? 我知道订单无法保证。
这会导致很多任务阻塞吗?
这安全吗?
private static StringBuilder sb = new StringBuilder();
private static async Task AccessTheWebAsync()
{
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(@"http://www.google.com/");
sb.Append(response.StatusCode).Append(Environment.NewLine);
}
static void Main(string[] args)
{
List<Task> tasks = new List<Task>();
for (int i = 0; i < 10; i++)
tasks.Add(AccessTheWebAsync());
Task.WaitAll(tasks.ToArray());
Console.Write(sb.ToString());
Console.ReadLine();
}