Winforms UI控件在线程期间变为只读,在其中使用这些控件 [英] Winforms UI controls become read only during threading which using these controls inside it
问题描述
我有一个GUI,我有下面的控件,
工具栏,组合框,ListBox,上下文菜单,ListView和Treeview。
问题是..我在一个线程中传递上层控件继续更新这些控件..所以同时我的线程运行,我无法点击任何GUI控件..是的我可以看到列表框中的更新值和其他控件,但用户无法在线程运行期间单击任何GUI控件。
private void MethodXYZ()
{
这 .Invoke( new MethodInvoker( delegate ()
{
// loigc here
mnuItemDatabase.Enabled = false // 当我尝试从逻辑中移除Invoke时,此行显示错误
}));
}
ThreadStart TS1 = new ThreadStart(MethodXYZ);
线程Th1 = 新线程(TS1);
Th1.Name = ExecuteTestSession;
Th1.IsBackground = true ;
Th1.Start();
我在this.INVOKE中写的整个线程函数还有一件事,原因我将线程方法放在Invoke里面我正在使用它内部的UI控件,如果我删除Invoke,则抛出异常,
跨线程操作无效:控制表单名称'从创建它的线程以外的线程访问。
我尝试过:
i尝试使用后台工作者和任务工厂调用线程方法。
看起来你正在开始一个后台线程它只是调用调用
。这会将所有逻辑推回到UI线程,就好像您从未在第一时间启动后台线程一样。唯一的区别是,你现在有第二个线程等待逻辑完成。
删除单片调用
调用,而是将每个调用访问或更新UI控件的调用包装在自己的调用
调用中。
所以,而不是:
this.Invoke(新的MethodInvoker(委托{
//读取UI
//逻辑
//更新UI
//更多逻辑
...
});
使用:
this.Invoke(新的MethodInvoker(委托{
//读取UI
});
//这里的逻辑
这个.Invoke(新的MethodInvoker(委托{
//更新UI
});
//更多逻辑
...
i have one GUI where i have below controls,
Tool Bar ,Combo Box, ListBox, Context Menu, ListView and Treeview.
problem is.. i am passing upper controls in one Thread which continues updating these controls.. so meanwhile my thread runs, i am not able to click on any of GUI controls.. yes i can see updated value in list box and other controls but user not able to click on any GUI controls during thread runs.
private void MethodXYZ()
{
this.Invoke(new MethodInvoker(delegate()
{
// loigc here
mnuItemDatabase.Enabled = false //this line shows error when I am trying to remove Invoke from Logic
}));
}
ThreadStart TS1 = new ThreadStart(MethodXYZ);
Thread Th1 = new Thread(TS1);
Th1.Name = "ExecuteTestSession";
Th1.IsBackground = true;
Th1.Start();
one more thing entire thread function i wrote inside "this.INVOKE" ,reason i put thread method inside Invoke is i am using UI controls inside it, and its throw below exception if i remove Invoke,
"Cross-thread operation not valid: Control 'form name' accessed from a thread other than the thread it was created on."
What I have tried:
i tried with Background worker and Task factory call to thread method.
It looks like you're starting a background thread which simply callsInvoke
. This pushes all of the logic back onto the UI thread, as if you'd never started a background thread in the first place. The only difference is, you now have a second thread stuck waiting for the logic to finish.
Remove the monolithicInvoke
call, and instead wrap each call that accesses or updates a UI control in its ownInvoke
call.
So, instead of:
this.Invoke(new MethodInvoker(delegate{ // Read UI // Logic // Update UI // More logic ... });
use:
this.Invoke(new MethodInvoker(delegate{ // Read UI }); // Logic here this.Invoke(new MethodInvoker(delegate{ // Update UI }); // More logic ...
这篇关于Winforms UI控件在线程期间变为只读,在其中使用这些控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!