views:

113

answers:

3

Consider the below program

myThread = new Thread(
                        new ThreadStart(
                            delegate
                            {
                                Method1();
                                Method2();
                            }
                            )
                            );

Is it that 2 threads are getting called parallely(multitasking) or a single thread is calling the methods sequentially?

It's urgent.

+5  A: 

That's a single thread.

Method2() won't be called before Method1() ends.

If you want Method1() and Method2() to be each in a separate thread you can do:

myThread1 = new Thread(new ThreadStart(Method1));
myThread2 = new Thread(new ThreadStart(Method2));

and start them:

myThread1.Start();
myThread2.Start();

now both can be running concurrently.

Useful resources:

Bakkal
Is it possible to make a multithread for the same using the same delegate style.. I mean , if I fire 2 sepearte delegate, will it be multithreaded.
Newbie
Could you please write a pseudo code(rough) for the sake of understanding
Newbie
NB. in the second case, anonymous methods (introduced by `delegate` keyword) are not needed: `new Thread(new ThreadStart(Method1));`
el.pescado
So do you mean, for multitasking I need to do thread1 = Thread(new ThreadStart(Method1)); thread2 = Thread(new ThreadStart(Method2)); and then thread1.join();thread2.join();
Newbie
@Newbie, I tried to edit the answer. To start a thread you call `Start()` on it. What `Join()` does is block (wait) until the thread finishes execution. You should read the links I referenced.
Bakkal
+3  A: 

Is it that 2 threads are getting called parallely(multitasking)

You could check it empirically: declare methoda Method1 and Method2 this way:

public void Method1 () {
    for (int i = 0; i < 10; i++) {
        System.Console.WriteLine ("Method1: {0}", i);
        Thread.Sleep (2000); // 2 seconds
    }
}

public void Method2 () {
    for (int i = 0; i < 10; i++) {
        System.Console.WriteLine ("Method2: {0}", i);
        Thread.Sleep (2000); // 2 seconds
    }
}

And then see whether they are executed sequentially or parallel.

or a single thread is calling the methods sequentially?

You could check it, say, analytically. How many Thread objects are you creating? What method are you passing to created threads?

You create only one Thread object, and this thread is to execute this anonymous method:

delegate {
    Method1();
    Method2();
}

This anonymous method, as can be seen clearly, will execute Method1, then Method2.

el.pescado
A: 

C# 3: Create and start seperate threads. To wait for them to finish, call Thread.Join on all of them.

C# 4: Threading.Tasks.Parallel.Invoke( () => Method1(), () => Method2() );

Jonathan Allen
Means(c#3.0) for multitasking I need to do thread1 = Thread(new ThreadStart(Method1)); thread2 = Thread(new ThreadStart(Method2)); and then thread1.join();thread2.join();
Newbie