c# - C#中的静态方法、静态字段和多线程

标签 c# .net multithreading

我有 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 应该是线程安全的。

关于c# - C#中的静态方法、静态字段和多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13209691/

相关文章:

c# - Silverlight:将服务调用和文件处理移至后台线程

c# - WPF 针对 .NET 4.5 但 Windows 要求在应用程序运行时安装 .NET 3.5

.net - 如何将 DataTable.Select() 的结果绑定(bind)到 ListBox 控件?

Java客户端/服务器线程快速通信消息时出现空指针异常

multithreading - CPU效率公式

c# - 必须注册 .tlb 文件吗?

c# - MVC 中的 P3P header 信息

c# - WPF 中的 3d 矢量计算

.net - Ninject 适合生产应用吗?

java - 没有看到静态类变量从在单独线程中运行的同一包中的另一个类更改