1. 程式人生 > >多線程:子線程執行過程中調用主線程

多線程:子線程執行過程中調用主線程

ring this 方法 his tca error ren ESS string

直接在子線程中調用方法,線程的ID為3,通過Post則為1

執行結果:

2018-09-13 11:21:11:1735 : 主線程:1

2018-09-13 11:21:16:0583 : 子線程:3

2018-09-13 11:21:16:0739 : ShowForm:1發送失敗!

2018-09-13 11:21:16:1051 : ShowForm:3發送失敗!

 public class TestClass
    {

        private SynchronizationContext mainThreadSynContext;
        public
void SendTestResult(string Url, string TestResult) { mainThreadSynContext = SynchronizationContext.Current; Thread t = new Thread(p => Start(Url, TestResult)); t.Start(); LogWriteUtility.Instance.LogWrite("主線程:"+Thread.CurrentThread.ManagedThreadId.ToString()); }
private void Start(string url, string testResult) { try { Thread.Sleep(TimeSpan.FromSeconds(5)); LogWriteUtility.Instance.LogWrite("子線程:" + Thread.CurrentThread.ManagedThreadId.ToString()); throw new Exception("發送失敗!
"); } catch (Exception ex) { //SendOrPostCallback myDelegate; //myDelegate = new SendOrPostCallback(ShowForm); mainThreadSynContext.Post(ShowForm, ex); this.ShowForm(ex); } } private void ShowForm(object state) { Exception ex = state as Exception; LogWriteUtility.Instance.LogWrite("ShowForm:" + Thread.CurrentThread.ManagedThreadId.ToString()+ex.Message); //ErrorForm form = new ErrorForm(); //form.ShowDialog(); } }

多線程:子線程執行過程中調用主線程