本文介绍了是三元运算符(?:)线程在C#中安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑让 currentPrice 和 100 ...
之间的人数较多的以下两种备选方案 INT价格= currentPrice> 100? currentPrice:100 INT价格= Math.Max(currentPrice,100)我提出这个问题,因为我在想其中 currentPrice 变量可以被其它线程编辑的内容。
在第一种情况下可以... 价格获得比 100 ?
$ b $低的值b我正在考虑以下内容:
如果(currentPrice→100){ // currentPrice在这里编辑。 价格= currentPrice; }解决方案
这不是线程安全的。
:只是快捷方式正常如果,所以你的如果样本等同于 一个 - 你可以得到价格低于100,如果有这个代码之外没有锁定
Consider the following two alternatives of getting the higher number between currentPrice and 100...
int price = currentPrice > 100 ? currentPrice : 100 int price = Math.Max(currentPrice, 100)I raised this question because I was thinking about a context where the currentPrice variable could be edited by other threads.
In the first case... could price obtain a value lower than 100?
I'm thinking about the following:
if (currentPrice > 100) { //currentPrice is edited here. price = currentPrice; }解决方案
It is not threadsafe.
?: is just shortcut for normal if, so your if sample is equivalent to ? one - you can get price lower than 100 if there is no locking outside this code.
更多推荐
是三元运算符(?:)线程在C#中安全吗?
发布评论