daixinet

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
  211 随笔 :: 0 文章 :: 115 评论 :: 68万 阅读

    WPF不同线程之间的控件是不同访问的,为了能够访问其他线程之间的控件,需要用Dispatcher.Invoke执行一个新的活动即可。

例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public void SetNotes(string notes)
{
    if (Dispatcher.Thread != Thread.CurrentThread)
    {
        this.txtNote.Dispatcher.Invoke(new Action(() =>
        {
            this.txtNote.Text += notes;
            this.txtNote.Text += "\r";
            this.txtNote.ScrollToEnd();
        }));
    }
    else
    {
        this.txtNote.Text += notes;
        this.txtNote.Text += "\r";
        this.txtNote.ScrollToEnd();
    }
}

 WinForm中:

复制代码
private delegate void delegateCrossThread(string message);
        private void SetStatus(string message)
        {
            if (this.m_StatusLabel.InvokeRequired == true)
            {
                delegateCrossThread ct = new delegateCrossThread(SetStatus);
                this.Invoke(ct, new object[] { message });
            }
            else
            {
                this.m_StatusLabel.Text = message;
                this.m_StatusLabel.Refresh();
            }
        }
复制代码

3、异步打开窗口

复制代码
            Thread newWindowThread = new Thread(new ThreadStart(ThreadStartingPoint));
            newWindowThread.SetApartmentState(ApartmentState.STA);
            newWindowThread.Start(); 

  private void ThreadStartingPoint()
        {
            SurveyStatWindow surveyStatDialog = new SurveyStatWindow();
            if (m_StatDataTable != null)
            {
                surveyStatDialog.TimeData = m_StatDataTable;
                surveyStatDialog.Init();
            }
            surveyStatDialog.ShowDialog();
        }
复制代码

 4、全局异步调用

     Application.Current.Dispatcher.Invoke(new Action(() =>
     {
         AddText();
     }));
 
     this.Dispatcher.Invoke(new Action(() =>
     {
         AddText();
     }));
 
Application.Current.Dispatcher.Invoke(new Action(delegate { AddText();}));
 

 

 

posted on   daixinet.com  阅读(5001)  评论(0)    收藏  举报
编辑推荐:
· 如何统计不同电话号码的个数?—位图法
· C#高性能开发之类型系统:从 C# 7.0 到 C# 14 的类型系统演进全景
· 从零实现富文本编辑器#3-基于Delta的线性数据结构模型
· 记一次 .NET某旅行社酒店管理系统 卡死分析
· 长文讲解 MCP 和案例实战
阅读排行:
· C#高性能开发之类型系统:从 C# 7.0 到 C# 14 的类型系统演进全景
· 管理100个小程序-很难吗
· 基于Blazor实现的运输信息管理系统
· 如何统计不同电话号码的个数?—位图法
· 微信支付功能的设计实现与关键实践(UniApp+Java)全代码
点击右上角即可分享
微信分享提示