委托和调用 [英] Delegate and Invoke
问题描述
调试时收到此错误:跨线程操作无效:xxxxxxxx访问ftrom一个线程而不是它创建的线程。
我一直在阅读,我知道我需要创建一个委托并使用xxxxx。调用....但我对此非常困惑
发生的事情是我创建了一个新的线程,它将在线收集一些数据然后分配它到xxxxx.Text属性
我被卡住了:(
ps。我已经知道 :System.Windows.Forms.Control.CheckForIllegalCrossT hreadCalls = true / false;我不想使用它。
C#.NET2.2
OK!我用它实现了它:
i receive this error when debugging: Cross-thread operation not valid: "xxxxxxxx" accessed ftrom a thread other than the thread it was created on.
I''ve been reading and i know that i will need to create a delegate and use xxxxx.invoke....but im very confused about it
What is going on is that i created a new thread that will collect a piece of data online and then assign it to xxxxx.Text property
im stuck :(
ps. i already know about: System.Windows.Forms.Control.CheckForIllegalCrossT hreadCalls = true/false; and i dont want to use this.
C#.NET2.2
OKAY! i achieved it using this:
推荐答案
你使用的例子有点令人困惑,我会提供一些更简洁的例子。
The example you used is a little confusing, I will provide a bit more concise one.
您使用的示例有点令人困惑,我将提供更简洁的示例。
The example you used is a little confusing, I will provide a bit more concise one.
委托用于捆绑操作/任务,为了我们的目的,它用于确保在特定(gui)线程上执行操作。
SetTextCallback d = new SetTextCallback( SetSomeText);
//创建我创建的类型的委托的实例,其中包含SetSomeText和SetSomeText。作为调用的函数。 (函数应该与委托声明匹配)
this.Invoke(d,new object [] {text});
//这告诉表单使用object []作为传递给委托函数的参数调用给定的委托。
// Invoke()在GUI线程上执行委托操作
A delegate is used to bundle an operation/task, for our sake its used to make sure an operation is carried out on the specific(gui) thread.
SetTextCallback d = new SetTextCallback(SetSomeText);
//creates an instance of the delegate of the type i created, with "SetSomeText" as the function to call. (Function should match the delegate declaration)
this.Invoke(d, new object[] { text });
//this tells the form to invoke the given delegate with an object[] as the parameters to pass to the delegate''s function.
//Invoke() performs the delegate action on the GUI thread
这篇关于委托和调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!