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方法中創建的子線程會被中止。