use*_*950 1 c# multithreading synchronization web-services windows-services
我正在开发一个窗口服务应用程序,我的窗口服务将在特定时间间隔(例如 3 分钟)调用其中一个 Web 服务。我将从网络服务中获取数据库中的数据,并使用该数据发送电子邮件。
如果我的数据库表中有大量行,则发送邮件需要一些时间。我在这里遇到了问题:窗口服务发送第一个请求,它将处理一些记录集。因此,在 Web 服务处理它时,窗口服务在完成第一个请求之前向 Web 服务发送另一个请求。因此,每当 Web 服务收到来自 Windows 服务的新请求时,它就会一次又一次地从 db 获取相同的记录。
任何人都可以建议我如何锁定先前的请求,直到它完成其工作或以其他方式处理这种情况吗?
网络服务调用:
protected override void OnStart(string[] args)
{
timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
timer.Interval = 180000;
timer.AutoReset = false;
timer.Enabled = true;
}
Run Code Online (Sandbox Code Playgroud)
内部方法
using (MailWebService call = new MailWebService())
{
try
{
call.ServiceUrl = GetWebServiceUrl();
System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
call.CheckMailQueue();
}
catch (Exception ex)
{
LogHelper.LogWriter(ex);
}
finally
{
}
}
Run Code Online (Sandbox Code Playgroud)
该显示器类此方案的伟大工程。以下是如何使用它的示例:
// This is the object that we lock to control access
private static object _intervalSync = new object();
private void OnElapsedTime(object sender, ElapsedEventArgs e)
{
if (System.Threading.Monitor.TryEnter(_intervalSync))
{
try
{
// Your code here
}
finally
{
// Make sure Exit is always called
System.Threading.Monitor.Exit(_intervalSync);
}
}
else
{
//Previous interval is still in progress.
}
}
Run Code Online (Sandbox Code Playgroud)
还有一个重载TryEnter允许您指定进入该部分的超时时间。