多线程:子线程执行过程中调用主线程
2021-07-01 02:04
标签:调用 man reads pos 发送 art res main second 直接在子线程中调用方法,线程的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发送失败! 多线程:子线程执行过程中调用主线程 标签:调用 man reads pos 发送 art res main second 原文地址:https://www.cnblogs.com/sportdog/p/9639480.html 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();
}
}