本文整理汇总了C#中System.Array.AcquireWriteLock方法的典型用法代码示例。如果您正苦于以下问题:C# Array.AcquireWriteLock方法的具体用法?C# Array.AcquireWriteLock怎么用?C# Array.AcquireWriteLock使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Array
的用法示例。
在下文中一共展示了Array.AcquireWriteLock方法的2个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: AcquireReadWriteLocks_ReadWrite_Blocks
public void AcquireReadWriteLocks_ReadWrite_Blocks()
{
var name = Guid.NewGuid().ToString();
using (var sma = new Array<byte>(name, 10))
{
using (var smr = new Array<byte>(name))
{
// Acquire write lock
sma.AcquireWriteLock();
// Should block (and fail to reset write signal)
Assert.IsFalse(smr.AcquireReadLock(10));
sma.ReleaseWriteLock();
smr.AcquireReadLock();
// Should block (and fail to reset read signal)
Assert.IsFalse(sma.AcquireWriteLock(10));
smr.ReleaseReadLock();
}
}
}
示例2: AcquireWriteLock_ReadWrite_LocksCorrectly
public void AcquireWriteLock_ReadWrite_LocksCorrectly()
{
var name = Guid.NewGuid().ToString();
Random r = new Random();
int bufSize = 1024;
byte[] data = new byte[bufSize];
byte[] readBuf = new byte[bufSize];
bool readIsFirst = false;
bool readBlocked = false;
int syncValue = 0;
// Fill with random data
r.NextBytes(data);
using (var sma = new Array<byte>(name, bufSize))
{
// Acquire write lock early
sma.AcquireWriteLock();
using (var smr = new Array<byte>(name))
{
var t1 = Task.Factory.StartNew(() =>
{
if (System.Threading.Interlocked.Exchange(ref syncValue, 1) == 0)
readIsFirst = true;
// Should block until write lock is released
smr.AcquireReadLock();
if (System.Threading.Interlocked.Exchange(ref syncValue, 3) == 4)
readBlocked = true;
smr.CopyTo(readBuf);
smr.ReleaseReadLock();
});
System.Threading.Thread.Sleep(10);
var t2 = Task.Factory.StartNew(() =>
{
var val = System.Threading.Interlocked.Exchange(ref syncValue, 2);
if (val == 0)
readIsFirst = false;
else if (val == 3)
readBlocked = false;
System.Threading.Thread.Sleep(10);
sma.Write(data);
System.Threading.Interlocked.Exchange(ref syncValue, 4);
sma.ReleaseWriteLock();
});
Task.WaitAll(t1, t2);
Assert.IsTrue(readIsFirst, "The read thread did not enter first.");
Assert.IsTrue(readBlocked, "The read thread did not block.");
// Check data was written before read
for (var i = 0; i < readBuf.Length; i++)
{
Assert.AreEqual(data[i], readBuf[i]);
}
}
}
}