Hi,
I'm trying to add to a buffer, that might be in use by other threads. To
synchronise around the buffer, I'm using a monitor. However, if the add
takes too long, I'd like to delegate it to a threadpool thread and then
carry on doing my own thing:
int mSecondsToWait = 100; // try for 0.1 sec
if (Monitor.TryEnter(syncRoot, mSecondsToWait))
{
//only add if not flushing or if no other item is being added
try
{
buffer.Add(item);
}
finally
{
Monitor.Exit(syncRoot);
}
}
else
{
ThreadPool.QueueUserWorkItem(delegate(object state)
{
lock(syncRoot){buffer.Add(item);}
});
}
My questions are:
1) Is this the best way to do this? This request to add might be called many
times per second, and so calls to buffer.Add might pile up. That's when I'd
like to call a thread. Can you ask the monitor how many threads are waiting
on it already?
2) Whats the best amount of time to wait for an exclusive lock? My initial
thought is that I should only wait as long as it takes to create a thread,
but then there's no way of knowing when a lock might be relinquished so
that's kind of arbitrary. I guess I should wait for the lenth of time it
takes to add an item to the buffer. Should I wait at all?
3) This strategy doesn't retain ordering of items added (since the next item
in queue might get the lock if the front gives up and spawns a thread). Is
there a strategy that does?
Thanks!
Shak