Reputation: 1111
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?
Upvotes: 0
Views: 1439
Reputation: 55448
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:
Upvotes: 7
Reputation: 70337
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() );
Upvotes: 1
Reputation: 19236
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
.
Upvotes: 4