How to write correct static methods - multithread safe

 ̄綄美尐妖づ 提交于 2019-12-07 17:29:52

问题


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 ?


回答1:


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.

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!



来源:https://stackoverflow.com/questions/1992475/how-to-write-correct-static-methods-multithread-safe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!