-3

C# でコードを記述してプロセス内にスレッドを作成し、別のプロセスで 2 分ごとに ( JQuerySetIntervalを使用して) Jquery ajax を呼び出して同じスレッドを作成します。

しかし、スレッドが既にスレッドプールに存在する場合、スレッドを作成するための新しいリクエストは何もしません。

これどうやってするの?

アップデート -

求人掲載の仕事をしています。ユーザーがJob Site. しばらくして(〜2分)ジョブステータス(ジョブポストかどうか)を取得する必要があるため、このためにサーバー側コードでスレッドを作成し、スレッドを2分間スリープさせますreturn false. 同時に、クライアント側で 2 分間の時間間隔を設定し、ajax 関数を呼び出して同じスレッドを作成します。

マイコード -

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 "";
            }
        }

private string GetCBJobStatus(string TransactionId)
        {
            try
            {
                string PostJobStatus = "";
                JobManagement oJobManagement = new JobManagement();
                HttpWebRequest JobStatusreq = (HttpWebRequest)WebRequest.Create("http://dpi.careerbuilder.com/webservices/RealTimeJobStatus.asmx/GetJobPostStatus?sTGDID=" + TransactionId);
                JobStatusreq.Method = "GET";
                using (WebResponse Statusresponse = JobStatusreq.GetResponse())
                {
                    using (StreamReader rd = new StreamReader(Statusresponse.GetResponseStream()))
                    {
                        string JobStatus = rd.ReadToEnd();
                        // - Post job status
                        PostJobStatus = JobStatus.ToString().Substring(JobStatus.LastIndexOf("<PostStatus>"));
                        PostJobStatus = PostJobStatus.Substring(PostJobStatus.IndexOf("<PostStatus>"), PostJobStatus.IndexOf("</PostStatus>")).Split('>')[1];
                    }
                }
                if (PostJobStatus == "Success")
                {
                    return "Job Posted Successfully";
                }
                else if (PostJobStatus == "Queued")
                {
                    return "Job Queued up";
                }
                return "";
            }
            catch (Exception ex)
            {
                return "";
            }
        }

スレッドの C# 関数 -

// -- Make thread
        private void GetJobStatusForCB(object objJobStatus)
        {
            try
            {
                System.Threading.Thread.Sleep(20000);
                string TransactionDID = objJobStatus.ToString().Split(':')[0];
                string JobStatus = "";
                JobManagement oJobManagement = new JobManagement();
                JobStatus = oJobManagement.GetCBJobStatus(TransactionDID);    

               if (JobStatus == "Job Queued up")
                {
                    System.Threading.ThreadPool.QueueUserWorkItem(new WaitCallback(oJobManagement.GetJobStatusForCB), (object)objJobStatus);
                }

            }
            catch (Exception ex)
            {

            }            
        }

一定間隔で呼び出す 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 "";
        }

上記のコードでは、jquery ajaxユーザーがポスト ジョブをクリックしたときにメインが実行されます。JobPostWeb メソッドを使用してジョブの最初のステータスを取得します。ステータスを取得した場合は、関数Job Queued upを使用してジョブ ステータスを取得するためのスレッドを呼び出しGetJobStatusForCBます。この関数sleepの現在のプロセスに 2 分間、return falseクライアントでジョブ ステータスを取得し、クライアント側SetIntervalを 2 分間セットアップします。この間隔で、私Jquery ajaxは仕事のステータスを取得するために別のものを呼び出します。この ajax では、 web method を呼び出しますGetJobStatusMethod。Webメソッドでは、最初にジョブのステータスを確認し、取得した場合はJob Queued up別のスレッドを呼び出してステータスを取得します. このステムで私の問題が発生しました-ジョブステータスを取得するためにスレッドが既に実行されている場合、別のスレッドを作成する必要がないためです。Timeset-time-intervalを変更したくありません。

だから、皆さんは私の本当の問題を理解していると思います。ご協力いただきありがとうございます。

4

1 に答える 1

2

You can use a pattern like this to ensure that if this particular method is started in a new thread pool thread it will do nothing if a previous instance is already running.

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);
            }
        }
    }
}
于 2013-07-09T14:03:57.440 に答える