是三元运算符(?:)线程在C#中安全吗?

编程入门 行业动态 更新时间:2024-10-27 04:35:36
本文介绍了是三元运算符(?:)线程在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#中安全吗?

本文发布于:2023-11-07 22:24:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1567601.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   运算符

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!