Issue creating a parameterized thread

Tyler Treat picture Tyler Treat · Mar 1, 2011 · Viewed 8.8k times · Source

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.

Answer

Dan Tao picture Dan Tao · Mar 1, 2011

Frustratingly, the ParameterizedThreadStart delegate type has a signature accepting one object parameter.

You'd need to do something like this, basically:

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

private static void Bar(int x)
{
    // do work
}