Reputation: 69
I was just wondering if there was a way to make a method wait until the previous method called completed execution without using threads. For exmaple, if there are two method calls,
{
A();
B();
}
I want B() to start running only when A has completed. Is there a way to do this without using threads, in c#?
Upvotes: 3
Views: 11246
Reputation: 112752
It is the default for statements to execute sequentially. Method calls make no difference.
This is even true, if a user clicks on a button while a method is running. In this case, the button click handler (like MyButton_Click) will wait for execution until the other method terminates its execution. This happens, because both methods are executed on the same thread, the so-called UI-thread.
Upvotes: 1
Reputation: 8190
Without using threads (as long as the calls are synchronous, which is the default) this is the default behavior.
For example:
Class Foo
{
var returnVal = A();
returnVal = B();
Console.WriteLine(returnVal.ToString());
}
B() will only run after A() anyway, and the .ToString() will print out the string representation of returnVal after B() has completed.
To make it do anything else, in fact, you would have to use threads and/or asynchronous calls.
Upvotes: 3
Reputation: 2068
it will automatically. You could also do this:
Example:
public static void Main(string[] args){
int i = 0;
i = A();
i = B();
System.Console.WriteLine(i);
}
public int A(){
return 1;
}
public int B(){
return 2;
}
Output: 2
Upvotes: 0
Reputation: 1214
If you execute two methods sequentially, and neither of them are called asynchronously, the first method will block execution of the second method until the first method returns.
A(); B(); will actually call them sequentially.
Upvotes: 1
Reputation: 727077
That is exactly what happens, unless A()
starts a new thread.
Upvotes: 2
Reputation: 152644
If you're not spinning off separate threads that will happen by default.
Upvotes: 3