1
  1. There has a Collection variable and an Add method at my WCF servcie side. The Add method would log some records to the Collection while something trigger . Here are the requirements: Now at the client Side, there has a Thread to read the Collection at WCF service side every second and remove the recorde read before and display them to the foreground.

My question is : How to Control the conccur of reading and writing would be better.( is not thread safe, so there will get duplicate values while reading it)

Currently I use a Timer to concurrency it, when the timer event is triggered, make the Timer stop untill the reading ended. And then let the Timer start(to prevent the timer Event not executed completely , triggered the next Operation again). I use Monitor.TryEnter as thread lock, and the code is like the following:

void ReadFromService()
{
//do........
timer.start();//
}


Timer timer=new Timer(1000);

timer.Elapsed +=(s,e)=>{
timer.stop();
ReadFromService();
};
timer.start();

I think this is not a good idea, I hope someone can give me something good suggestion.

Steve Townsend
  • 53,498
  • 9
  • 91
  • 140
ulee
  • 21
  • 4

2 Answers2

0

It would be preferable not to have a timer in your Reader client. It's not that concurrency is especially difficult, it's just plain inefficient to poll over a communication channel.

You could instead have the Add method trigger an event in the Reader client to either pass it the added records, or have that event act as a trigger to read an updated snapshot of the collection, and then the Service locks the Collection appropriately before returning the new snapshot.

This is a limited form of the Observer pattern, and easily extensible if you have more full collection readers, or new readers that wanted to see changes of different subsets of data from the collection.

Info on WCF events (callbacks) here.

Community
  • 1
  • 1
Steve Townsend
  • 53,498
  • 9
  • 91
  • 140
0

Have a look at the

ConcurrentList<T>

class at this link: http://www.deanchalk.me.uk/post/Task-Parallel-Concurrent-List-Implementation.aspx

Roy Dictus
  • 32,551
  • 8
  • 60
  • 76