C#强制执行语句的顺序

C#强制执行语句的顺序

本文介绍了C#强制执行语句的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是关于C#中执行保证的顺序(大概是.Net)。我给出了一些我知道要比较的Java示例。



For Java(来自Java Concurrency in Practice)

所以代码

  y = 10; 
x = 5;
a = b + 10;

实际上可以分配a = b + 10在分配y = 10之前



在Java中(来自同一本书)

所以在Java中

  y = 10; 
synchronized(lockObject){
x = 5;
}
a = b + 10;

y = 10和x = 5保证在a = b + 10之前运行(我不要不知道y = 10是否保证在x = 5之前运行。



C#代码对C#语句的执行顺序有什么保证

  y = 10; 
lock(lockObject){
x = 5;
}
a = b + 10;

我特别感兴趣的答案可以提供明确的参考或其他一些非常有意义的理由作为保证像这样很难测试,因为它们是关于允许编译器做什么的,而不是它每次都做什么,因为当它们失败时,当线程以错误的顺序触发时,你将很难重现间歇性的错误。

解决方案

,§ 10.10说(我引用):

其他CLI标准同样可以从 gratis 获得ISO








但如果你担心多线程问题,你需要深入研究标准并理解有关原子性的规则。并非每项操作都必须是原子的。如果你是多线程并且调用引用除局部变量之外的任何东西的方法(例如,实例或类(静态)成员)而没有通过 lock 序列化访问,那么互斥量,信号量或者其他一些序列化技术,你会让自己对竞争条件开放。


My question is about order of execution guarantees in C# (and presumably .Net in general). I give Java examples I know something about to compare with.

For Java (from "Java Concurrency in Practice")

So the code

  y = 10;
  x = 5;
  a = b + 10;

may actually assign a=b+10 Before assigning y = 10

And in Java (from the same book)

so in Java

 y = 10;
 synchronized(lockObject) {
     x = 5;
 }
 a = b + 10;

y = 10 and x = 5 are guaranteed to both run before a = b + 10 (I don't know whether y = 10 is guaranteed to run before x = 5).

What guarantees does C# code make for the order of execution for the C# statements

 y = 10;
 lock(lockObject) {
     x = 5;
 }
 a = b + 10;

I am particularly interested in an answer that can provide a definitive reference or some other really meaningful justification as guarantees like this are hard to test because they are about what the compiler is allowed to do, not what it does every time and because when they fail you are going to have very hard to reproduce intermittent bugs when threads hit things in just the wrong order.

解决方案

ISO 23270:2006 — Information technology—Programming languages—C#, §10.10 says (and I quote):

The other CLI standards are likewise available gratis from the ISO at

But if you are worried about multi-threading issues, you'll need to dig deeper into the standards and understand the rules about atomicity. Not every operation is warranted to be atomic. If you are multi-threaded and invoking methods that reference anything but local variables (e.g., instance or class (static) members) without serializing access via lock, a mutex, a semaphore, or some other serialization technique, you are leaving yourself open to race conditions.

这篇关于C#强制执行语句的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 15:23