我有一个 WCF 接口使用的控制器类(我有 SOAP 和 REST 接口)。
因此,当有人打电话时,SubmitJob
我会将其传递给控制器。
在控制器功能中,它将把它保存到队列中。
现在,在我的项目中,我有一个在此类中定义的队列:
public static class WebServiceControllerStatic
{
static ConcurrentQueue<WebServiceModels.Job> jobqueue = new ConcurrentQueue<WebServiceModels.Job>();
然后我有这两种方法,一种将信息放入队列,然后另一种启动线程来处理队列。
public static WebServiceModels.Job[] JobQueue
{
set
{
value.AsParallel().ForAll(i => jobqueue.Enqueue(i));
}
}
public static void ProcessUpdateJobQueue()
{
Action UpdateJob = () =>
{
if (jobqueue.IsEmpty)
return;
int cnt = 0;
Parallel.For(0, jobqueue.Count, new ParallelOptions() { MaxDegreeOfParallelism = 20 },
(j) =>
{
cnt++;
});
};
if (processUpdateJobThread == null)
{
processUpdateJobThread = new System.Threading.Thread(() =>
{
while (true)
{
UpdateJob();
UpdateJob();
System.Threading.Thread.Sleep(10000);
}
});
processUpdateJobThread.Start();
}
}
在我的控制器方法中,每当在您的情况下进行 SubmitJob 调用时,我都会调用它:
WebServiceControllerStatic.JobQueue = jobs;
WebServiceControllerStatic.ProcessUpdateJobQueue();
所以,我有一个队列来保存需要处理的内容,还有一个线程每隔一段时间就会启动以处理队列中的任何内容。
这很适合我的需要。
我使用 ConcurrentQueue 主要是因为我将同时更新和从队列中删除。