Jad*_*ias 42 .net c# multithreading volatile
以下代码
using System.Threading;
class Test
{
volatile int counter = 0;
public void Increment()
{
Interlocked.Increment(ref counter);
}
}
Run Code Online (Sandbox Code Playgroud)
引发以下编译器警告:
"A reference to a volatile field will not be treated as volatile"
Run Code Online (Sandbox Code Playgroud)
我在这里做错了什么来提出这个警告?为什么编译器会对此发出警告?
Jon*_*eet 31
基本上警告是,当您通过引用传递volatile字段时,调用代码不知道以易失性方式处理它.对于可能无关紧要的Interlocked.Increment,由于方法的性质 - 但是如果您使用Interlocked ,则无论如何都不需要变量.
一般来说,我想我会避免将两者混合在一起 - 如果你使用的是Interlocked,那么到处都是(使用Interlocked.CompareExchange(ref counter, 0, 0)它来阅读).我不能说我个人经常使用volatile.对于简单的计数器,我可能会使用Interlocked,但我更可能使用锁来执行大多数任务.
Rob*_*ser 30
用这个:
#pragma warning disable 420
// M
// dM
// MMr
// 4MMML .
// MMMMM. xf
// . "MMMMM .MM-
// Mh.. +MMMMMM .MMMM
// .MMM. .MMMMML. MMMMMh
// )MMMh. MMMMMM MMMMMMM
// 3MMMMx. 'MMMMMMf xnMMMMMM"
// '*MMMMM MMMMMM. nMMMMMMP"
// *MMMMMx "MMMMM\ .MMMMMMM=
// *MMMMMh "MMMMM" JMMMMMMP
// MMMMMM 3MMMM. dMMMMMM .
// MMMMMM "MMMM .MMMMM( .nnMP"
// =.. *MMMMx MMM" dMMMM" .nnMMMMM*
// "MMn... 'MMMMr 'MM MMM" .nMMMMMMM*"
// "4MMMMnn.. *MMM MM MMP" .dMMMMMMM""
// ^MMMMMMMMx. *ML "M .M* .MMMMMM**"
// *PMMMMMMhn. *x > M .MMMM**""
// ""**MMMMhx/.h/ .=*"
// .3P"%....
// nP" "*MMnx
if(Interlocked.CompareExchange(ref isLoaded, 1, 0) != 0)
return;
#pragma warning restore 420
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8607 次 |
| 最近记录: |