横穿螺纹 [英] crossing betweeen threads
本文介绍了横穿螺纹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
>我在我的项目中定义了线程,并获得了有关交叉线程和表单线程的异常
我该如何解决此问题?
>i am defined thread in my project and get exception about crossing my thread and thread of my form
how can i resolve this problem?
推荐答案
我认为您的意思是"CrossThread错误"-正常的原因是当您尝试从线程访问UI控件时并没有创造它们.您不能这样做:您必须使用Invoke来使UI线程更新控件,否则会出现错误.
这是我的方法:
I assume you mean a "CrossThread error" - the normal reason for this is when you try to access UI controls from a thread that didn''t create them. You can''t do that: you have to use Invoke to cause the UI thread to update the controls, or you get an error.
This is how I do it:
private void AddNewTab(string tabName)
{
if (InvokeRequired)
{
Invoke(new MethodInvoker(delegate { AddNewTab(tabName); }));
}
else
{
TabPage tp = new TabPage(tabName);
myTabControl.TabPages.Add(tp);
}
}
解决方案1是一个很好的解决方案,但是如果您使用此解决方案,则可以编写一段简短的代码:
Solution 1 is a good solution, but if you use this solution you can write a shorter code snipped:
private void AddNewTab(string tabName)
{
Invoke(new MethodInvoker(delegate()
{
Tabpage tp = new TabPage(tabName);
myTabControl.TabPages.Add(tp);
}));
}
我的工作:
我不需要检查InvokeRequired
布尔值,如果不需要调用,则也可以调用该方法,但是没有问题.
我用匿名方法创建一个标签页.
希望这会有所帮助.
What I do:
I don''t check the InvokeRequired
boolean, if you don''t need invoking, then the method is invoked also, but there''s no problem.
In an anonymous method I create a tab page.
Hope this helps.
这篇关于横穿螺纹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文