C# WebService中任務處理線程創建子線程后


        protected void WriteLog(string message)
        {
            lock (lockObject)
            {
                var file = System.IO.File.AppendText("C:\\log.txt");
                file.WriteLine(message);
                file.Close();
            }
        }

        protected void asyctest(int threadid)
        {

            this.WriteLog(string.Format("主線程({0})的子線程({1})開始", threadid, AppDomain.GetCurrentThreadId()));

            System.Threading.Thread.Sleep(10000);

            ProcessThread thread = this.GetThreadbyID(threadid);

            this.WriteLog(string.Format("主線程({0}: state: {1})的子線程({2})結束", threadid, thread == null ? -1 : (int)thread.ThreadState, AppDomain.GetCurrentThreadId()));

        }

        protected ProcessThread GetThreadbyID(int id)
        {
            foreach (ProcessThread item in System.Diagnostics.Process.GetCurrentProcess().Threads)
            {
                if (item.Id == id)
                {
                    return item;
                }
            }

            return null;
        }

        protected delegate void delegatetest(int threadid);

        [WebMethod]
        public void test()
        {
            this.WriteLog(string.Format("主線程({0})開始", AppDomain.GetCurrentThreadId()));

            

            for (int i = 0; i < 10; i++)
            {
                delegatetest currentDaliyCollect = new delegatetest(asyctest);
                IAsyncResult iADaliyCollect = currentDaliyCollect.BeginInvoke(AppDomain.GetCurrentThreadId(), null, null);
                if (iADaliyCollect.IsCompleted)
                {
                    currentDaliyCollect.EndInvoke(iADaliyCollect);
                }

            }
        }

  

結論:

C# WebService中任務處理線程創建子線程后,此任務處理線程並沒有退出銷毀,而是ThreadState切換成Wait狀態,所以子線程也不會被中止,而得以繼續執行。

 

本來是想驗證,父線程退出后,子線程是否會被強制中止。時間關系沒有驗證,至少驗證了在webservice,不用擔心在rpc方法中創建的子線程會被中止。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM