how to start a thread with in-place function?

  • Thread starter Thread starter parsifal
  • Start date Start date
P

parsifal

In Java I can start a thread and write the function in-place. So, you
could do, in pseudocode:

def someFunc:
thread.new( def summit: doSomeStuff() )

How can I do that in C#?
 
Are you refering to anonymous methods?

They are not present in 1.1 they are in 2.0 though.
 
You need to pass an instance of the ThreadStart delegate to the
constructor for your thread class, like so:

Thread t = new Thread(new ThreadStart(doSomeStuff));

Hope this helps.
 
If using 2.0 you can write the ThreadStart method in place as Ignacio
pointed. Here is an example.

public static void Main()
{
ThreadStart doSomeStuff = delegate()
{
// Put your thread code here.
};

Thread thread = new Thread(doSomeStuff);
thread.Start();
thread.Join();
}

Brian
 
Okay so here's what I want to do: I need to start multiple threads that
do the same things, but with different parameters. What's the simplest
way to do that?
 
Oh interesting. That's exactly what I want, but my Visual Studio is
complaining about my use of delegate in "delegate() {..}". It says
"Invalid expression term 'delegate'". Do I need to tell it to use 2.0?
What am I doing wrong?
 
parsifal,

If you are using .NET 2.0, have your method take an object parameter,
and then pass the parameter to the Start method on the Thread instance.

If you are using .NET 1.1 and before, then what you want to do is
encapsulate your logic into a type which holds all the information needed to
perform the processing. Then, you set the values on an instance of the
type, and then pass the delegate to your Thread instance. For each separate
instance, you pass a separate instance of your class.
 
I have installed .NET 2.0, but I'm using VS.NET 7. In the About box,
it says .NET Framework 1.0. How can I change that?
 
parsifal said:
I have installed .NET 2.0, but I'm using VS.NET 7. In the About box,
it says .NET Framework 1.0. How can I change that?

I don't think you can??
 
Back
Top