Search code examples
c#multithreadingparameterized

Issue creating a parameterized thread


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.


Solution

  • 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
    }