如何编写正确的静态方法 - 多线程安全 [英] How to write correct static methods - multithread safe

查看:129
本文介绍了如何编写正确的静态方法 - 多线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于我假设静态方法不应该像第一片段被writen,还是我错了?

As I assume static methods shouldn't be writen like the first snippet , or am I wrong ?

public static class ExtensionClass
{
 private static SomeClass object1;
 private static StringBuilder sb;

 private static string DoSomething()
 {
    sb.AppendLine(object1.SomeValue);
 }

 public static string ExtensionMethod(this HtmlHelper helper, SomeClass _object1)
 {
    object1 = _object1;
    sb = new StringBuilder();

    DoSomething();

    return sb.ToString();
 }
}



于是我想出了这一点:

So I come up with this:

public static class ExtensionClass
{
  private static string DoSomething(ref StringBuilder _sb,SomeClass object1)
  {
    _sb.AppendLine(object1.SomeValue);
  }

  public static string ExtensionMethod(this HtmlHelper helper, SomeClass _object1)
  {
    SomeClass object1 = _object1;
    StringBuilder sb = new StringBuilder();

    DoSomething(ref sb,_object1);

    return sb.ToString();
  }



}

}

这是最后的片段多线程安全?这应该是一个扩展方法,所以它不能被非静态的。或者是有路过的非静态物体周围的静态方法没有更好的办法?

Is this last snippet multithread safe ? This should be an extension method,so it cant be non-static. Or is there any better way of passing non-static object in a static method around ?

推荐答案

第二个片段是作为multithread-安全的,因为你传递进去的对象。如果周围的一些其他方法渣土用的HtmlHelper或SomeClass的ExtensionMethod运行时,那么你可能会碰到的问题。但ExtensionMethod都有自己的StringBuilder(不像你的第一个片段),以ExtensionMethod这么多次调用将得到不同的StringBuilders和一切都会好起来的那前面。

The second snippet is as multithread-safe as the objects you're passing into it. If some other method mucks around with the HtmlHelper or the SomeClass while ExtensionMethod is running, then you may hit problems. But ExtensionMethod gets its own StringBuilder (unlike your first snippet) so multiple calls to ExtensionMethod will get different StringBuilders and all will be well on that front.

您是正确的,静态的方法不应该这样写的第一个片段。正如你已经意识到,如果线程A调用ExtensionMethod和线程B调用ExtensionMethod而线程A仍然在那里, SB 成员将被改为引用新的StringBuilder。全部是A迄今所做的工作都将丢失,A和B将从此被追加到同一StringBuilder的,有意想不到的结果!

You are correct that static methods shouldn't be written like the first snippet. As you have realised, if Thread A calls ExtensionMethod, and Thread B calls ExtensionMethod while Thread A is still in there, the sb member will be changed to refer to a new StringBuilder. All the work that A has done so far will be lost, and A and B will henceforth be appending to the same StringBuilder, with undesirable results!

这篇关于如何编写正确的静态方法 - 多线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆