ref重點
1.傳遞至 ref 參數的引數,在傳遞之前必須先初始化。
2.不能將ref和out用於async修飾詞定義的非同步方法。
3.有進有出
out關鍵字
基本上跟ref一樣
想要多個回傳值的時候,可以使用out
ref跟out在使用上有很微小的差距
使用out的話,他不需要在被調用前初始化
但是調用者需要在返回之前指定輸出的參數
另一方面,可以用這樣去想
out類似於將方法附加返回值,也就是回傳多個值啦
多thread共用變數時,可以用內建的 Interlocked.Increment、Interlocked.Decrement
來Lock變數
static void SumTo10000V3()
{
for (int i = 1; i <= 10000; i++)
{
Interlocked.Increment(ref Total3);
}
}
static void SumTo10000V4()
{
for (int i = 1; i <= 10000; i++)
{
lock (_lockV4)
{
Total4++;
}
}
}
public static void SumTo10000V5()
{
for (int i = 1; i <= 10000; i++)
{
// Acquires the exclusive lock
Monitor.Enter(_lockV5);
try
{
Total5++;
}
finally
{
// Releases the exclusive lock
Monitor.Exit(_lockV5);
}
}
}
static int Total6 = 0;
static object _lockV6 = new object();
public static void SumTo10000V6()
{
for (int i = 1; i <= 10000; i++)
{
bool lockTaken = false;
//1.
//Monitor.Enter(Object obj, Boolean lockTaken)
//1.1.
//Acquires an exclusive lock on the specified object,
//and atomically sets a value that
//indicates whether the lock was taken.
//1.2.
//Boolean lockTaken
//The result of the attempt to acquire the lock, passed by reference.
//The input must be false.
//The output is true if the lock is acquired
Monitor.Enter(_lockV6, ref lockTaken);
try
{
Total6++;
}
finally
{
// Releases the exclusive lock
if (lockTaken)
Monitor.Exit(_lockV6);
}
}
}
沒有留言:
張貼留言