|
-
Feb 8th, 2006, 02:38 PM
#1
Thread Starter
Frenzied Member
[RESOLVED] how to create new 'Thread' when delegate has parameters...
I have this procedure that looks like this:
Code:
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?
-
Feb 8th, 2006, 02:39 PM
#2
Re: how to create new 'Thread' when delegate has parameters...
What are your compile errors?
-
Feb 8th, 2006, 05:36 PM
#3
Thread Starter
Frenzied Member
Re: how to create new 'Thread' when delegate has parameters...
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?
-
Feb 8th, 2006, 06:15 PM
#4
Re: how to create new 'Thread' when delegate has parameters...
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.
-
Feb 8th, 2006, 07:36 PM
#5
Re: how to create new 'Thread' when delegate has parameters...
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:
Code:
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.
-
Feb 9th, 2006, 11:31 AM
#6
Thread Starter
Frenzied Member
Re: how to create new 'Thread' when delegate has parameters...
-
Feb 9th, 2006, 04:24 PM
#7
Re: how to create new 'Thread' when delegate has parameters...
Don't forget to resolve your thread from the Thread Tools menu if you have all the information you need.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|