How to write the right static methods - multi-threaded safe

Do I suppose static methods should not be written as the first fragment, or am I mistaken?

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 came 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 multithreaded safe? This should be an extension method, so it cannot be non-stationary. Or is there a better way to skip a non-static object in a static method?

+3
source share
1 answer

, , . - HtmlHelper SomeClass, ExtensionMethod , . ExtensionMethod StringBuilder ( ), ExtensionMethod StringBuilders, .

, . , Thread A ExtensionMethod, Thread B ExtensionMethod, Thread A , sb , StringBuilder. , A , , A B StringBuilder !

+8

Source: https://habr.com/ru/post/1727104/


All Articles