Thread safe Static methods how

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Claes R

    Thread safe Static methods how

    Hi !

    I would like this class method to be thread safe.

    public static ArrayList List(DateTime date)
    {
    ArrayList l = new ArrayList();
    l.Add(new ListItemInfo( 1, "S1010"));
    ......
    return l;
    }

    How do i accomplish this in a scalable way ?

    lock works on a object, not class (or ??)

    Would his suffice ??
    public static ArrayList List(DateTime date)
    {
    Monitor.Enter()
    ArrayList l = new ArrayList();
    l.Add(new ListItemInfo( 1, "S1010"));
    ......
    return l;
    Monitor.Exit()
    }

    Alternatives ??

    Thanks
    Claes
  • Jon Skeet [C# MVP]

    #2
    Re: Thread safe Static methods how

    Claes R <anonymous@disc ussions.microso ft.com> wrote:[color=blue]
    > I would like this class method to be thread safe.
    >
    > public static ArrayList List(DateTime date)
    > {
    > ArrayList l = new ArrayList();
    > l.Add(new ListItemInfo( 1, "S1010"));
    > ......
    > return l;
    > }[/color]

    That is already thread-safe - your not accessing any shared data (in
    the code you've shown, anyway).

    --
    Jon Skeet - <skeet@pobox.co m>
    Pobox has been discontinued as a separate service, and all existing customers moved to the Fastmail platform.

    If replying to the group, please do not mail me too

    Comment

    • Miha Markic

      #3
      Re: Thread safe Static methods how

      Hi,

      You might provide a static object for locking;

      private static object lockingObject = new Object();

      and use it for locking:

      public static ArrayList List(DateTime date)
      {
      lock(lockingObj ect )
      {
      // your code
      }
      }

      --
      Miha Markic - RightHand .NET consulting & software development
      miha at rthand com

      "Claes R" <anonymous@disc ussions.microso ft.com> wrote in message
      news:3e9301c3aa af$e9eb3350$a60 1280a@phx.gbl.. .[color=blue]
      > Hi !
      >
      > I would like this class method to be thread safe.
      >
      > public static ArrayList List(DateTime date)
      > {
      > ArrayList l = new ArrayList();
      > l.Add(new ListItemInfo( 1, "S1010"));
      > ......
      > return l;
      > }
      >
      > How do i accomplish this in a scalable way ?
      >
      > lock works on a object, not class (or ??)
      >
      > Would his suffice ??
      > public static ArrayList List(DateTime date)
      > {
      > Monitor.Enter()
      > ArrayList l = new ArrayList();
      > l.Add(new ListItemInfo( 1, "S1010"));
      > ......
      > return l;
      > Monitor.Exit()
      > }
      >
      > Alternatives ??
      >
      > Thanks
      > Claes[/color]


      Comment

      Working...