如何跨线程访问UI控件

当进行一些耗时的操作的时候,让UI所在的主线程进行处理,是不合适的,因为这样会使UI在操作的过程中停止响应。这时候需要使用多线程的方法进行处理。但是有一个问题就是一般情况下不能对UI控件进行跨线程的操作,下面是对这个问题的解决办法。

1、WinForm程序中

 a、第一种方法是使用BackgroundWorker控件,实例代码如下。

BackgroundWorker Demo 

b、 使用Thread/ThreadStart的跨线程操作控件,实例代码如下。

OperaControsInThreads Demo 

2、 WPF程序中, 使用Thread/ThreadStart的跨线程操作控件。

在WPF程序中, 控件没有InvokeRequired属性,这时候我们需要使用Dispatcher.CheckAccess()方法。 下面是在线程函数中调用的事件响应函数的例子。

        void OnDoWork(int, testInt, string testString)
        
{
            
if (!Dispatcher.CheckAccess())
            
{
                Dispatcher.Invoke(DispatcherPriority.Send, 
new OnDoWorkHandler(OnDoWork),  testInt, testString);
            }

            
else
            
{
                
//The code doing works. We can access the controls in UI.
            }

        }
原文地址:https://www.cnblogs.com/pdfw/p/1518991.html