Thread safe Static methods how

C

Claes R

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
 
J

Jon Skeet [C# MVP]

Claes R said:
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;
}

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

Miha Markic

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(lockingObject )
{
// your code
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top