sportdog

导航

 

直接在子线程中调用方法,线程的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();
        }
    }

 

posted on 2018-09-13 11:24  sportdog  阅读(899)  评论(0编辑  收藏  举报