5

I'm not sure how to explain what I'm trying to ask so consider the following example:

int number;

void ChangeNumber()
{
    number++;
    UseNumber(number);
}

void UseNumber(int value)
{
    // use number
}

I'm using this simple example to try to find out if when scripts are ran, it waits for one task to be completed before moving onto the next. For example, is UseNumber(number) only called once the number has been incremented before it?

Consider instead of number++ I was making a call to another method which did some complex calculations and also made it's own calls to other methods, would UseNumber(number) still wait for all that to run before being called? If not, would a callback be a good option for that situation to ensure previous tasks are completed first?

8
  • 4
  • 2
    Program sequences within the same 'thread' are always ordered, regardless of any 'small delay' between/during executing instructions. (The async/await keywords can slice up code to make this appear to not be the case: it's all tasks [and threads] in the background, and does not apply here.) Jan 15, 2020 at 17:39
  • 3
    Short answer to all your questions: Yes. (until you start getting into things like multi-threading, which it sounds like you have a ways to go before you'll get into that) Jan 15, 2020 at 17:40
  • 1
    C# is not "scripts" and there are no tasks when calling methods.
    – i486
    Jan 15, 2020 at 17:47
  • 2
    @user2864740: Let's make your statement slightly more precise. The execution of effects within a thread happen in an order that is equivalent to the program order as written, as observed by that thread. However, (1) a second thread may observe a different order than original program order, and (2) a third thread may observe a different order than either of the first two threads. C# does not guarantee that there is a consistent "true order" observed by all threads; threads may disagree as to the ordering of effects. Jan 16, 2020 at 18:17

5 Answers 5

20

The short answer is: C# behaves sensibly; you are guaranteed that the effects of earlier statements are observed by later statements.

The long answer is: things are more subtle than that when you look at more complex situations.

First off: C# does not guarantee that the order in which code actually runs is the same as the order in which it occurs in the program. The guarantee that is made is more subtle than that: the language guarantees that the program will appear to run as though it ran in the order the code occurred in the program.

This subtlety might need some more explanation. Suppose you had:

int foo = 1;
int bar = 2;
foo += 1;
bar += 1;
Console.WriteLine(foo);
Console.WriteLine(bar);

This program must increment foo and bar before the console writes, and the console writes must happen foo, then bar. However, the behaviour of the program fragment above is the same as:

int foo = 1;
int bar = 2;
bar += 1;
foo += 1;
Console.WriteLine(foo);
Console.WriteLine(bar);

And that has the same behaviour as this program fragment:

Console.WriteLine(2);
Console.WriteLine(3);

Since the observed side effects are identical in each case, C# is permitted to run any of these programs instead of the code as originally written.

Things then get a lot more complicated when you add:

  • Iterator blocks
  • Asynchronous workflows
  • Concurrency
  • Unmanaged code interop
  • Finalization

The restrictions on how C# promises to preserve effect ordering get quite complicated when you throw those in; describing any of those could be an extremely long answer of its own, so if you have questions, try asking a second, more focussed question.

6

C#, as most programming languages, runs all statements synchronously. Which is essentially the same as saying all statements are executed in the order encountered, one at a time.

However, C# supports asynchronous programming, at that point the programmer is in charge of what waits for what.

So, yes, in the example you post UseNumber will only be called when number++ finishes.

1

Programs can be optimized and/or reordered during both compilation and run-time execution. Or there could be small "delays" during execution. However, the specification still guarantees the 'expected' ordering.

Per the Specification (ECMA-334/2017):

8.10 Execution order

Execution of a C# program proceeds such that the side effects [(such as writing to a variable)] of each executing thread are preserved at critical execution points. A side effect is defined as a read or write of a volatile field, a write to a nonvolatile variable, a write to an external resource, and the throwing of an exception ..

Data dependence is preserved within a thread of execution. That is, the value of each variable is computed as if all statements in the thread were executed in original program order.

• Initialization ordering rules are preserved [between threads of execution] ..

• The ordering of side effects [between threads of execution] is preserved with respect to volatile reads and writes ..

The strong guarantee (in bold) applies to a single thread of executions. Multiple threads can interleave executions and introduce a variety of [unexpected] race conditions. However, each thread's execution order is well defined.

The async/await keywords are syntactic sugar (for Tasks) and are complimentary to this guaranteed execution order. If using async/await (which is a concurrency model) and/or threads is appropriate really depends on what 'UseNumber' does. There has been no rational given for such and spurious usages of concurrency/parallelism add complexity and overheads.

1

To add onto other answers, which seem to focus on how all synchronous operations are, well, synchronous. There actually can be a delay (or rather an IL nop instruction) that the compiler inserts between calls. It's only true when you compile your code with optimisations off (i.e. debug configuration) and serves a purpose of allowing you to step through your code. The easiest way to see it in action, you need to look at IL generated for your method when you compile it with Debug and Release targets.

// optimisations off
IL_0000:  nop         
IL_0001:  nop         
IL_0002:  nop         
IL_0003:  ret         

<Main>g__ChangeNumber|0_0:
IL_0000:  nop         
IL_0001:  ldarg.0     
IL_0002:  ldfld       UserQuery+<>c__DisplayClass0_0.number
IL_0007:  stloc.0     
IL_0008:  ldarg.0     
IL_0009:  ldloc.0     
IL_000A:  ldc.i4.1    
IL_000B:  add         
IL_000C:  stfld       UserQuery+<>c__DisplayClass0_0.number
IL_0011:  ldarg.0     
IL_0012:  ldfld       UserQuery+<>c__DisplayClass0_0.number
IL_0017:  call        UserQuery.<Main>g__UseNumber|0_1
IL_001C:  nop         
IL_001D:  ret         

<Main>g__UseNumber|0_1:
IL_0000:  nop         
IL_0001:  ret   

and compare it to the case when debug flag is set

IL_0000:  ret         

<Main>g__ChangeNumber|0_0:
IL_0000:  ldarg.0     
IL_0001:  ldfld       UserQuery+<>c__DisplayClass0_0.number
IL_0006:  stloc.0     
IL_0007:  ldarg.0     
IL_0008:  ldloc.0     
IL_0009:  ldc.i4.1    
IL_000A:  add         
IL_000B:  stfld       UserQuery+<>c__DisplayClass0_0.number
IL_0010:  ldarg.0     
IL_0011:  ldfld       UserQuery+<>c__DisplayClass0_0.number
IL_0016:  call        UserQuery.<Main>g__UseNumber|0_1
IL_001B:  ret         

<Main>g__UseNumber|0_1:
IL_0000:  ret
1

Yes. Simple statements like the ones you describe are executed one after the other, so execution would "wait" for one of them to finish before moving on to the next.

That said, C# does support concurrency. You can launch different threads or better still Tasks that run concurrently. For execution that doesn't block, you can also define asynchronous functions. Check out this article for an introduction.

Another example where the order of statements can change is through the delayed execution achieved by iterator blocks. Consider the following code:

void DisplayColours()
{
    var colours = GetColours();
    foreach (var colour in colours)
    {
        Console.WriteLine($"The next colour is: {colour}");
    }
}

IEnumerable<string> GetColours()
{
    yield return "red";
    yield return "green";
    yield return "blue";
}

In the example above, when you call GetColours() to assign it to colours, none of the code in GetColours() is executed. The individual yield return statements of GetColours() are executed each time the foreach iterator moves to a new item in the colours IEnumerable.

2
  • 2
    You say "in newer versions of .NET", which I suppose is technically true -- the best kind of true. The Task class shipped eleven years ago; is the supposition of your statement that the original poster might be using a pre-2009 version of .NET? That seems like an odd supposition to make; I'd be curious to know how you arrived at that. Jan 16, 2020 at 18:13
  • 2
    Hahaha that is an excellent point Eric! Sorry, this is merely due to me having worked with old code bases a lot.
    – Philip Atz
    Jan 17, 2020 at 11:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.