VBForums >
.NET >
C# > [RESOLVED] how to create new 'Thread' when delegate has parameters...
Click to See Complete Forum and Search --> : [RESOLVED] how to create new 'Thread' when delegate has parameters...
benmartin101
Feb 8th, 2006, 01:38 PM
I have this procedure that looks like this:
private void proc1(int x, int y)
{
//code
}
//i'm trying to create thread here
Thread t;
t = new Thread(new ThreadStart(proc1)) //also tried ThreadStart(proc1(x,y))
t.Start();
This code does not compile. How do I do this correctly?
Hack
Feb 8th, 2006, 01:39 PM
What are your compile errors?
benmartin101
Feb 8th, 2006, 04:36 PM
I get this error when my delegate has a parameter and i declare my thread like this:
t = new Thread(new ThreadStart(proc1))
error:
Method 'Prog.Form1.btnGoProc(int)' does not match delegate 'void System.Threading.ThreadStart()'
when:
t = new Thread(new ThreadStart(proc1(int_value)))
error:
Method name expected
I guess a better question would be, is it possible to create a new thread with a delegate that has parameters?
jmcilhinney
Feb 8th, 2006, 05:15 PM
No it isn't possible. If you want to give your thread data then you can set class-level variables that the new thread can then retrieve. Another option is to create a new object specifically for the new thread. You pass the data for your thread to properties of the object and then set a method of the object as the thread entry point.
jmcilhinney
Feb 8th, 2006, 06:36 PM
Note that .NET 2.0 adds a new way to do what you want. You can create a ParameterizedThreadStart delegate instead of a ThreadStart. You can then pass a single Object to Thread.Start as a parameter for the method actiang as the thread entry point. You could rewrite your code like this in C# 2005:private void proc1(Point p)
{
//code
}
//i'm trying to create thread here
Thread t;
t = new Thread(new ParameterizedThreadStart(proc1)) //also tried ThreadStart(proc1(x,y))
t.Start(new Point(10, 20));MSDN2 points out that this method is not type-safe as you can pass any object to Thread.Start and the compiler will not check whether it is the correct type for the method that will be called. It goes on to recommend the second method I mentioned above as a better way to ensure type-safety.
benmartin101
Feb 9th, 2006, 10:31 AM
thanks.
jmcilhinney
Feb 9th, 2006, 03:24 PM
Don't forget to resolve your thread from the Thread Tools menu if you have all the information you need.
vbforums.com
Copyright Internet.com Inc., All Rights Reserved.