views:

460

answers:

1

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 ?

+6  A: 

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!

itowlson