问题创建参数化线程

Tyl*_*eat 11 c# multithreading parameterized

我在尝试使用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
    }
}
Run Code Online (Sandbox Code Playgroud)

我不确定我做错了什么,因为我在网上找到的例子似乎做了同样的事情.

Dan*_*Tao 17

ParameterizedThreadStart令人沮丧的是,委托类型具有接受一个object参数的签名.

你需要做这样的事情,基本上:

// This will match ParameterizedThreadStart.
private static void Bar(object x)
{
    Bar((int)x);
}

private static void Bar(int x)
{
    // do work
}
Run Code Online (Sandbox Code Playgroud)


dec*_*one 7

这是ParameterizedThreadStart看起来像:

public delegate void ParameterizedThreadStart(object obj); // Accepts object
Run Code Online (Sandbox Code Playgroud)

这是你的方法:

private static void Bar(int x) // Accepts int
Run Code Online (Sandbox Code Playgroud)

要使其工作,请将您的方法更改为:

private static void Bar(object obj)
{
    int x = (int)obj;
    // todo
}
Run Code Online (Sandbox Code Playgroud)