直接在子线程中调用方法,线程的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(); } }
原文地址:https://www.cnblogs.com/sportdog/p/9639480.html
时间: 2024-10-21 07:48:13