I am designing a windows service that consumes a web service. I have Timer instances running that trigger callback events once timers elapse, then a particular method within the web service is consumed. Since the timers are different and have different threads, it is possible right now for multiple threads to attempt consuming the web service simultaneously, which cannot occur.
I know there are some know idioms and methods for attacking this process. I essentially want to queue up requests to consume the service, then let it occur as the web service becomes available each time till the queue is empty. But I'm not sure of the devices nor am I familiar with multithreading in C#
Any help would be great!
Loading
Matthew CoxPosted May 29, 2010, 4:53 PM
I think I am getting a deadlock when attempting to lock in the Enqueue method right off the bat ... based on my reading ... I shouldn't be getting this issue since I obtain the lock by default the first time and make sure to wake other threads as well while in the lock
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using WinDriverService.PWS;
namespace WinDriverService
{
public class ProducerConsumer
{
private readonly object listLock = new object();
public enum ServiceType
{
Weather,
WeatherAlert,
EqAlert,
TsunamiAlert,
FloodAlert
};
private Queue<ServiceType> queue;
private PollingWebService pws;
public ProducerConsumer()
{
queue = new Queue<ServiceType>();
pws = new PollingWebService();
pws.Timeout = 600000;
}
public void Produce(ServiceType item)
{
lock (listLock)
{
queue.Enqueue(item);
Monitor.Pulse(listLock);
}
}
public PollerEntry[] Consume()
{
PollerEntry[] entries = null;
lock (listLock)
{
while (queue.Count == 0)
{
Monitor.Wait(listLock);
}
ServiceType type = queue.Dequeue();
if (type == ServiceType.Weather)
{
entries = pws.PollWeatherInfo();
}
else if (type == ServiceType.WeatherAlert)
{
entries = pws.PollWeatherAlerts();
}
}
Monitor.Pulse(listLock); //wake any threads waiting in this method to obtain lock
return (entries);
}
}
}
PJ MartinsPosted May 26, 2010, 5:07 PM