【发布时间】:2015-04-20 13:06:08
【问题描述】:
让一个包含文本框的表单和一个设置它的方法(以不安全的方式):
class Form
{
void SetTextBoxContent( String txt )
{
this._tb_TextBox.SetText( txt );
}
}
现在,如果我想让这个线程安全,我需要执行以下操作:
class Form
{
void SetTextBoxContent( String txt )
{
if( this._tb_TextBox.InvokeRequired )
this._tb_TextBox.Invoke( new DelegateSetTextBoxContentUnsafe( SetTextBoxContentUnsafe );
else
this.DelagSetTextBoxContentUnsafe( txt );
}
delegate void DelegateSetTextBoxContentUnsafe( String txt );
void SetTextBoxContentUnsafe( String txt )
{
this._tb_TextBox.SetText( txt );
}
}
对吗?现在,如果我想从本机线程调用 SetTextBoxContent() 怎么办?据我所知,没有办法调用对象的方法,所以我会将指向静态函数的指针传递到本机代码中。该函数将引用 Form 对象并自行执行方法调用:
class Form
{
static Form instance;
Form() { Form.instance = this }
static void CallSetTextBoxContent( String txt )
{
Form.instance.SetTextBoxContent( txt );
}
void SetTextBoxContent( String txt )
{
if( this._tb_TextBox.InvokeRequired )
this._tb_TextBox.Invoke( new DelagSetTextBoxContentUnsafe( SetTextBoxContentUnsafe );
else
this.DelagSetTextBoxContentUnsafe( txt );
}
delegate void DelagSetTextBoxContentUnsafe( String txt );
void SetTextBoxContentUnsafe( String txt )
{
this._tb_TextBox.SetText( txt );
}
}
现在我可以将我的静态函数 CallSetTextBoxContent() 传递到本机代码吗? 我在某处读到我需要为此创建一个委托。所以这意味着我需要为 CallSetTextBoxContent() 创建第二种类型的委托并将这个委托传递给本机代码? 2 个委托类型和 3 个函数来做一些看起来很简单的事情。方法对吗?
谢谢你:)
编辑:忘了提到我正在使用紧凑框架 2.0
【问题讨论】:
-
您不必创建自己的代表。使用现有的。
Action<string>应该与你的方法的签名相匹配。 -
谢谢。看起来更干净,但这可以传递给本机代码吗?
-
它就像任何其他代表一样。您可以将其传递给本机代码,就像为其他委托所做的那样。
标签: c# multithreading user-interface delegates pinvoke