Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 843
Tyler Treat Avatar asked Mar 01 '11 21:03

Tyler Treat


3 Answers

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
}
like image 92
Dan Tao Avatar answered Oct 17 '22 18:10

Dan Tao


This is what ParameterizedThreadStart looks like:

public delegate void ParameterizedThreadStart(object obj); // Accepts object

Here is your method:

private static void Bar(int x) // Accepts int

To make this work, change your method to:

private static void Bar(object obj)
{
    int x = (int)obj;
    // todo
}
like image 7
decyclone Avatar answered Oct 17 '22 19:10

decyclone


It is expecting an object argument so you can pass any variable, then you have to cast it to the type you want:

private static void Bar(object o)
{
    int x = (int)o;
    // do work
}
like image 3
toby Avatar answered Oct 17 '22 20:10

toby