R
Roger Down
Lets say I have a method UpdateCache() called from a single thread. I also
have a method GetCache() called from multiple threads. When UpdateCache() is
called, the cache updating is being processed. This can take time.
In the mean time, some of the multiple threads have called GetCache(), but
because the cache is being updated, I want them to wait for the
UpdateCache() to finish.
Something like this, in a very simplified code:
public void UpdateCache()
{
updating = true;
try { this.data = GetData(); }
finally { updating = false; }
}
public MyCache GetCache()
{
while( updating )
Thread.Sleep( 200 );
return this.data;
}
If I use lock for obtaining the same functionality, I guess it will be
something like this for the UpdateCache() method:
public void UpdateCache()
{
lock(this)
{
this.data = GetData();
}
}
But how can I rewrite this method ??
public MyCache GetCache()
{
?????
return this.data;
}
I've seen some examples using Monitor.Enter, Monitor.Wait, Monitor.Pulse and
Monitor.Exit on some lockable object before entering a synchronized section
of a code... but is there some solution where multiple thread only waits,
instead of locking an object ??
Maybe there are some better ways to solve this ??
Best of regards...
have a method GetCache() called from multiple threads. When UpdateCache() is
called, the cache updating is being processed. This can take time.
In the mean time, some of the multiple threads have called GetCache(), but
because the cache is being updated, I want them to wait for the
UpdateCache() to finish.
Something like this, in a very simplified code:
public void UpdateCache()
{
updating = true;
try { this.data = GetData(); }
finally { updating = false; }
}
public MyCache GetCache()
{
while( updating )
Thread.Sleep( 200 );
return this.data;
}
If I use lock for obtaining the same functionality, I guess it will be
something like this for the UpdateCache() method:
public void UpdateCache()
{
lock(this)
{
this.data = GetData();
}
}
But how can I rewrite this method ??
public MyCache GetCache()
{
?????
return this.data;
}
I've seen some examples using Monitor.Enter, Monitor.Wait, Monitor.Pulse and
Monitor.Exit on some lockable object before entering a synchronized section
of a code... but is there some solution where multiple thread only waits,
instead of locking an object ??
Maybe there are some better ways to solve this ??
Best of regards...