C# 如何检查“线程”是否已经存在?
我用C编写了一段代码,在一个进程中创建一个线程,在另一个进程中,使用Jquery SetInterval每隔2分钟调用一个Jquery ajax来创建一个相同的线程 但我想,若线程池中已经存在一个线程,那个么创建线程的新请求什么都不做 我该怎么做 更新- 我做招聘工作。当用户在作业网站上发布作业时。我需要在一段时间~2分钟后获得job Status job post或not,因此为此,我在服务器端代码上创建了一个线程,并休眠线程2分钟,然后返回false。同时,在客户端,我设置了一个2分钟的时间间隔,并调用一个ajax函数来创建相同的线程 我的密码-C# 如何检查“线程”是否已经存在?,c#,multithreading,threadpool,C#,Multithreading,Threadpool,我用C编写了一段代码,在一个进程中创建一个线程,在另一个进程中,使用Jquery SetInterval每隔2分钟调用一个Jquery ajax来创建一个相同的线程 但我想,若线程池中已经存在一个线程,那个么创建线程的新请求什么都不做 我该怎么做 更新- 我做招聘工作。当用户在作业网站上发布作业时。我需要在一段时间~2分钟后获得job Status job post或not,因此为此,我在服务器端代码上创建了一个线程,并休眠线程2分钟,然后返回false。同时,在客户端,我设置了一个2分钟的时间
var List = ["JobTitle", "JobDescription", "JobId"];
var JobDetails = JSON.stringify({ list: List });
$.ajax({
type: "POST",
url: "JobManagement.aspx/JobPost",
data: JobDetails,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (response.d.indexOf("Error") != -1) {
alert(response.d);
}
else if (response.d.indexOf("Job Queued up") != -1) {
var TransactionId = response.d.split(':')[1];
var GetJobStatusInterval = setInterval(function () {
$.ajax({
type: "POST",
url: "JobManagement.aspx/GetJobStatusMethod",
data: '{TransactionId: ' + "'" + TransactionId + "'" + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
clearInterval(GetJobStatusInterval);
},
failure: function (response) { }
});
}, 20000);
}
},
failure: function (response) { }
});
C代码-
[System.Web.Services.WebMethod()]
public static string JobPost(List<string> list)
{
try
{
string JobTitle = list[1];
string JobDescription = HttpUtility.HtmlEncode(list[2]);
string JobId = list[2];
string TransactionDID = "";
JobManagement oJobManagement = new JobManagement();
string JobData = "<JobTitle>" + JobTitle + "</JobTitle><JobDescription>" + JobDescription + "</JobDescription><JobId>" + JobId + "</JobId>";
XmlDocument soapEnvelopeXml = new XmlDocument();
//-- Creating web request with soap action
HttpWebRequest Soapreq = (HttpWebRequest)WebRequest.Create("http://dpi.careerbuilder.com/WebServices/RealTimeJobPost.asmx");
Soapreq.Headers.Add("SOAPAction", "http://dpi.careerbuilder.com/WebServices/RealTimeJobPost/ProcessJob");
Soapreq.ContentType = "text/xml; charset=utf-8";
Soapreq.Accept = "text/xml";
Soapreq.Method = "POST";
soapEnvelopeXml.LoadXml("<?xml version='1.0' encoding='utf-8'?><soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'><soap:Body><ProcessJob xmlns='http://dpi.careerbuilder.com/WebServices/RealTimeJobPost'><Job>" + JobData + "</Job></xmlJob></ProcessJob></soap:Body></soap:Envelope>");
//-- request to the server
using (Stream stream = Soapreq.GetRequestStream())
{
using (StreamWriter stmw = new StreamWriter(stream))
{
stmw.Write(soapEnvelopeXml.InnerXml.ToString());
}
}
// -- Getting response to the server
using (WebResponse response = Soapreq.GetResponse())
{
using (StreamReader rd = new StreamReader(response.GetResponseStream()))
{
string soapResult = rd.ReadToEnd();
Console.WriteLine(soapResult);
TransactionDID = soapResult.ToString().Substring(soapResult.LastIndexOf("<TransactionDID>"));
TransactionDID = TransactionDID.Substring(TransactionDID.IndexOf("<TransactionDID>"), TransactionDID.IndexOf("</TransactionDID>")).Split('>')[1];
}
}
string CurrentJobStatus = "";
CurrentJobStatus = oJobManagement.GetCBJobStatus(TransactionDID);
if (CurrentJobStatus == "Job Queued up")
{
string objJobStatus = TransactionDID + ":" + oJobManagement.oUser.ID.ToString() + ":" + oJobManagement.oUser.Organisation_ID.ToString();
System.Threading.ThreadPool.QueueUserWorkItem(new WaitCallback(oJobManagement.GetJobStatusForCB), (object)objJobStatus);
return "";
}
return "";
}
catch {
return "";
}
}
调用设置间隔的Web方法-
[System.Web.Services.WebMethod()]
public static string GetJobStatusMethod(string TransactionId)
{
try
{
string JobStatusCB = "";
JobManagement oJobManagement = new JobManagement();
oJobManagement.FillUserobj();
JobStatusCB = oJobManagement.GetCBJobStatus(TransactionId);
if (JobStatusCB == "Job Queued up")
{
// -- I want to check here if a thread is already running "Do Nothing"
// -- if "A Thread is already running" return false;
string objJobStatus = TransactionId + ":" + oJobManagement.oUser.ID.ToString() + ":" + oJobManagement.oUser.Organisation_ID.ToString();
System.Threading.ThreadPool.QueueUserWorkItem(new WaitCallback(oJobManagement.GetJobStatusForCB), (object)objJobStatus);
}
}
catch (Exception ex)
{
return "";
}
return "";
}
在上面的代码中,当用户单击post作业时,主jQueryAjax将运行。我使用JobPost web方法获取作业的第一个状态,如果获取作业排队状态,我将使用GetJobStatusForCB函数调用一个线程以获取作业状态。在这个函数中,将当前进程休眠2分钟并返回false,在客户端获取作业状态,并为everv 2分钟设置客户端设置间隔。在这个间隔中,我调用一个不同的Jquery ajax来获取作业状态。在这个ajax中,我将web方法称为GetJobStatusMethod。在web方法中,首先检查作业状态,若得到的作业已排队,则调用另一个线程以获取状态。在这个stem中,我的问题发生了——因为如果一个线程已经为get job status运行,我就不需要创建另一个线程。
我不想改变设定时间间隔的时间
所以,我想你们理解我真正的问题。感谢您的帮助。您可以使用这样的模式来确保如果在新的线程池线程中启动此特定方法,那么如果以前的实例已经在运行,它将不会执行任何操作
class Foo
{
//make static if this is called from different instances and should still
//be synchronized
private int isRunning = 0;
public void DoStuff()
{
if (Interlocked.Exchange(ref isRunning, 1) == 0)
{
try
{
DoRealStuff();
}
finally
{
Interlocked.Exchange(ref isRunning, 0);
}
}
}
}
你的问题没有什么意义。你需要解释更多。您是如何同时使用C和JQuery的?我不确定OP是否去过任何地方。我想让它看起来更像。我更新了我的问题,请看一看。@所有被否决的投票者,我不明白为什么要否决我的问题?+1如果请求间隔2分钟就行了。但是,如果可以同时调用DoStuff,则存在竞争条件。使用CompareExchange可能更好。
[System.Web.Services.WebMethod()]
public static string GetJobStatusMethod(string TransactionId)
{
try
{
string JobStatusCB = "";
JobManagement oJobManagement = new JobManagement();
oJobManagement.FillUserobj();
JobStatusCB = oJobManagement.GetCBJobStatus(TransactionId);
if (JobStatusCB == "Job Queued up")
{
// -- I want to check here if a thread is already running "Do Nothing"
// -- if "A Thread is already running" return false;
string objJobStatus = TransactionId + ":" + oJobManagement.oUser.ID.ToString() + ":" + oJobManagement.oUser.Organisation_ID.ToString();
System.Threading.ThreadPool.QueueUserWorkItem(new WaitCallback(oJobManagement.GetJobStatusForCB), (object)objJobStatus);
}
}
catch (Exception ex)
{
return "";
}
return "";
}
class Foo
{
//make static if this is called from different instances and should still
//be synchronized
private int isRunning = 0;
public void DoStuff()
{
if (Interlocked.Exchange(ref isRunning, 1) == 0)
{
try
{
DoRealStuff();
}
finally
{
Interlocked.Exchange(ref isRunning, 0);
}
}
}
}