arvialways
arvialways

Reputation: 69

Wait for a method to complete before executing the next in C#

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

Answers (6)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

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

AllenG
AllenG

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

tehdoommarine
tehdoommarine

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

Sheridan Bulger
Sheridan Bulger

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

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727077

That is exactly what happens, unless A() starts a new thread.

Upvotes: 2

D Stanley
D Stanley

Reputation: 152644

If you're not spinning off separate threads that will happen by default.

Upvotes: 3

Related Questions