![](/img/trans.png)
[英]ThreadPool.QueueUserWorkItem — is new WaitCallback() required?
[英]Convert string variable to WaitCallback in ThreadPool.QueueUserWorkItem
是否可以在ThreadPool.QueueUserWorkItem()
中将字符串变量作为WaitCallback参数传递
string myFunction="Go";
ThreadPool.QueueUserWorkItem(MyFunction);
public void Go(object obj)
{
//Do Something
}
您将需要使用反射。
例如:
WaitCallback callback = (WaitCallback) Delegate.CreateDelegate(
typeof(WaitCallback), this, myFunction);
ThreadPool.QueueUserWorkItem(callback);
要在不同的类中使用的方法,改变this
到目标实例。 如果要调用静态方法,请使用CreateDelegate
的重载,该重载将Type
作为第二个参数而不是对象。
您必须使用反射来获取方法:
var method = this.GetType().GetMethod(myFunction, new Type[] { typeof(object) });
var d = (WaitCallback)Delegate.CreateDelegate(typeof(WaitCallback), this, method);
ThreadPool.QueueUserWorkItem(d);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.