Reputation: 2984
I'm currently in the process of creating a class that has general methods that specialised methods of the class call. One of these general methods needs to get a method as parameter to use it to start a new thread.
My question is how this parameter must be done (thus what I must replace with, or what do I need to change in total to make it work as intended):
Class mytest
{
public void myPublicStarter()
{
Starter("Test", this.DoWork);
}
public void DoWork(object myIDString)
{
}
private void Starter(string myIDString, <METHOD> paramethod)
{
Thread myThread = new Thread(paramethod);
myThread.Start(myIDString);
}
}
Upvotes: 0
Views: 62
Reputation: 5820
Well, in .NET you have the concept of delegates, and you have Actions and Functions which are in fact just delegates.
A Function represents a function that takes some input parameters and has a return value. An action represents a method that takes some input parameters but doesn't return any value.
So it's depending on what you woud like to achieve.
Here's a demo sample:
static void Main(string[] args)
{
myPublicStarter();
}
public static void myPublicStarter()
{
Starter("Test", () => DoWork("My Id String Passed here"));
}
public static void DoWork(object myIDString)
{
Console.WriteLine(myIDString);
}
private static void Starter(string myIDString, Action paramethod)
{
paramethod.Invoke();
}
}
Note: I've made the classes static as I've converted it to a console application.
Now, to adapt the code to work with threads, you can use the following:
static void Main(string[] args)
{
myPublicStarter();
}
public static void myPublicStarter()
{
Starter("Test", x => DoWork("My Id String Passed here"));
}
public static void DoWork(object myIDString)
{
Console.WriteLine(myIDString);
}
private static void Starter(string myIDString, Action<object> paramethod)
{
Thread myThread = new Thread(x => paramethod(x));
myThread.Start(myIDString);
}
This will generate the exact same output as listed above.
Upvotes: 1
Reputation: 54427
When you create a new Thread
object you have to pass it a delegate, i.e. an object that refers to a method. That delegate must be type ThreadStart
if the entry method has no parameters and ParameterizedThreadStart
if it does. In your case, your DoWork
method has a parameter so the delegate type must be the latter. Because the paramethod
parameter is declared as that type, the compiler knows to cast this.DoWork
as that type when you call Starter
. If the method signature did not match that of the delegate then a compilation error would occur.
public void myPublicStarter()
{
Starter("Test", this.DoWork);
}
public void DoWork(object myIDString)
{
}
private void Starter(string myIDString, ParameterizedThreadStart paramethod)
{
Thread myThread = new Thread(paramethod);
myThread.Start(myIDString);
}
Upvotes: 2