我有1个静态类,1个字段和2个方法:
static class MyClass{
private static HttpClient client = new HttpClient();
private static string SendRequestToServer(int id)
{
Task<HttpResponseMessage> response = client.GetAsync("some string");
responseTask.ContinueWith(x => PrintResult(x));
return "some new value";
}
private static void Print(Task<HttpResponseMessage> task)
{
Task<string> r = task.Result.Content.ReadAsStringAsync();
r.ContinueWith(resultTask => Console.WriteLine("result is: " + resultTask.Result));
}
}
问题是,如果许多线程开始使用MyClass及其方法,是否会导致一些问题?
最佳答案 通过这些方法访问的所有资源都需要是线程安全的.在你的情况下,他们不是.如果您查看
HttpClient文档,它会指出:
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
您正在调用实例方法(client.GetAsync),这不保证是线程安全的,因此可能会给您带来问题.
为了缓解这种情况,您可以:
>在每次调用时创建一个新的(本地)HttpClient.
>同步对客户端的访问(例如使用锁).
另外,我不能告诉你PrintResult是否是线程安全的,但是Console.WriteLine应该是线程安全的.