Issue creating a parameterized thread
Asked Answered
Q

6

11

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.

Quail answered 1/3, 2011 at 21:31 Comment(0)
C
17

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
}
Christoffer answered 1/3, 2011 at 21:33 Comment(0)
M
7

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
}
Martino answered 1/3, 2011 at 21:35 Comment(0)
P
3

Method Bar should accept object parameter. You should cast to int inside. I would use lambdas here to avoid creating useless method:

public static void Foo(int x)
{
    ParameterizedThreadStart p = new ParameterizedThreadStart(o => Bar((int)o));
    Thread myThread = new Thread(p);
    myThread.Start(x);
}

private static void Bar(int x)
{
    // do work
}
Photon answered 1/3, 2011 at 21:33 Comment(0)
N
3

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
}
Nygaard answered 1/3, 2011 at 21:35 Comment(0)
F
3

You need to change Bar to

private static void Bar(object ox)
{
   int x = (int)ox;
   ...
}

The function you pass to ParameterisedThreadStart needs to have 1 single parameter of type Object. Nothing else.

Fairly answered 1/3, 2011 at 21:36 Comment(0)
B
1

Bar must take an object in parameter, not an int

private static void Bar(object x)
{ 
    // do work
}
Breeding answered 1/3, 2011 at 21:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.