创建参数化线程时出现问题
我在尝试使用 ParameterizedThreadStart 创建线程时遇到问题。这是我现在的代码:
public class MyClass
{
public static void Foo(int x)
{
ParameterizedThreadStart p = new ParameterizedThreadStart(Bar); // no overload for Bar matches delegate ParameterizedThreadStart
Thread myThread = new Thread(p);
myThread.Start(x);
}
private static void Bar(int x)
{
// do work
}
}
我不太确定我做错了什么,因为我在网上找到的示例似乎在做同样的事情。
I'm having problems trying to create a thread with a ParameterizedThreadStart. Here's the code I have now:
public class MyClass
{
public static void Foo(int x)
{
ParameterizedThreadStart p = new ParameterizedThreadStart(Bar); // no overload for Bar matches delegate ParameterizedThreadStart
Thread myThread = new Thread(p);
myThread.Start(x);
}
private static void Bar(int x)
{
// do work
}
}
I'm not really sure what I'm doing wrong since the examples I found online appear to be doing the same thing.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
令人沮丧的是,
ParameterizedThreadStart
委托类型具有接受一个object
参数的签名。基本上你需要做这样的事情:
Frustratingly, the
ParameterizedThreadStart
delegate type has a signature accepting oneobject
parameter.You'd need to do something like this, basically:
这是
ParameterizedThreadStart
的样子:这是您的方法:
要使其正常工作,请将您的方法更改为:
This is what
ParameterizedThreadStart
looks like:Here is your method:
To make this work, change your method to:
它需要一个对象参数,因此您可以传递任何变量,然后您必须将其转换为您想要的类型:
It is expecting an object argument so you can pass any variable, then you have to cast it to the type you want:
您需要将 Bar 更改为
您传递给 ParameterizedThreadStart 的函数需要有 1 个对象类型的单个参数。没有别的了。
You need to change Bar to
The function you pass to ParameterisedThreadStart needs to have 1 single parameter of type Object. Nothing else.
方法
Bar
应接受object
参数。您应该在内部强制转换为int
。我会在这里使用 lambda 来避免创建无用的方法:Method
Bar
should acceptobject
parameter. You should cast toint
inside. I would use lambdas here to avoid creating useless method:Bar
参数中必须采用object
,而不是int
Bar
must take anobject
in parameter, not anint