Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Waiting for process completion
#9
Ginteras,

Thanks for your help on this. I may try it or I may try to implement the more general ooncept of a session lock.

It seems that other languages have this problem too (no session lock). I attach an excerpt from http://www.codeproject.com/threads/WsSessionLock.asp

Regards, Bob

Session Lock

A session lock is very useful especially when enumerating or iterating through all the elements in a collection. Fortunately, the .NET collection classes support the concept of a session lock. Here is an illustration:

// create a synchronized version of a collection object
ArrayList list = ArrayList.Synchronized( new ArrayList() );

// fill it with elements
for(int i=0; i<20; i++)
list.Add( new BankAccount() );

// inside a thread procedure
int num = 0;
lock(list.SyncRoot) // this is a session lock
{
double Sum=0;
IEnumerator enm = list.GetEnumerator();
while(enm.MoveNext())
Sum += ((BankAccount)enm.Current).Balance;

Console.Out.WriteLine("Sum: {0}", list.Count, num);
}

Every .NET collection class has this SynRoot member. If a lock is applied on this member, then every other thread is prevented from modifying the collection. No elements inside the collection can be removed or even modified. And no elements can be added to that collection. The SyncRoot is really a very good feature. But it is only available with the collection classes.

Nevertheless, we can provide session lock capabilities to any class of our own design with just a few lines of code. Unlike Java, the .NET framework provides us with a Monitor object which is a kind of critical section or mutex. Let us rewrite the BankAccount class in C#.

public class BankAccount {
private double _amount;

// the account methods
public void deposit(double amount) {
lock(this) {
_amount += amount;
}
}
public void withdraw(double amount) {
lock(this) {
_amount -= amount;
}
}
public double Balance {
get {
lock(this) {
return _amount;
}
}
}


// here are the session lock methods
public lock() {
Monitor.Enter(this);
}
public unlock() {
Monitor.Exit();
}


Messages In This Thread

Forum Jump:


Users browsing this thread: 1 Guest(s)