Resource stack that waits if empty, until an element is pushed
I want to build a stack of resources that will be used by different threads, but want to block to calling thread up to a timeout until a resource becomes available. The method WaitUntilTheStackHasMember() is the part I am lacking. I though of using a method like the one described on MSDN's timer and autoreset event, but it got complicated.
Is there an easier way to do this?
Class ResStack
{
public TimeS开发者_JAVA百科pan TimeOut { get; set; }
private object lockSync;
private Stack<Resource> Resources;
ResStak()
{
// populate Stack
}
public void AddResource (Resource resource)
{
lock (lockSync)
{
Resource.Push(resource);
}
}
private Resource PopRes()
{
Resource res = null;
lock (lockSync)
{
if (Resources.Count > 0)
{
res = Resources.Pop();
}
else
{
WaitUntilTheStackHasMember() // Not implemented
}
}
return res;
}
If you can use .NET 4, the BCL added a BlockingCollection<T>
class that does exactly what you need. You can construct it with a ConcurrentStack<T>
to achieve blocking stack semantics.
You'll want to use the TryTake(out T, TimeSpan)
method for your timeout requirements.
Your method could repeatedly sleep and test until some time elapsed or a resource showed up. Have it return a flag indicating that it found a resource or timed out:
bool WaitUntilTheStackHasMember()
{
TimeSpan waitPeriod = TimeSpan.FromSeconds(10);
int sleepPeriod = 100; // milliseconds
DateTime startTime = DateTime.Now;
while ((Resources.Count == 0) && ((DateTime.Now - startTime) < waitPeriod))
{
System.Threading.Thread.Sleep(sleepPeriod);
}
return Resources.Count > 0;
}
精彩评论