C# thread 共用變數(C# thread lock)
C# thread 共用變數(C# thread lock)
資料來源: https://dotblogs.com.tw/jincode/2016/04/12/225954
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ThreadSumTest
{
class Program
{
static int threadCount = 0;
static object countLock=new object();
static void HelloThread(Object time)
{
Console.WriteLine("--START--Now{0},Thread{1}", ((DateTime) time).ToShortTimeString() , Thread.CurrentThread.ManagedThreadId);
Random ran = new Random();
Thread.Sleep(ran.Next(0,1000));
Console.WriteLine("--E N D--Now{0},Thread{1}", ((DateTime)time).ToShortTimeString(), Thread.CurrentThread.ManagedThreadId);
lock (countLock)
{
for (int i = 0; i < 10000; i++)
{
threadCount++;
}
}
}
static void Main(string[] args)
{
List<Thread> ThreadList=new List<Thread>();
for (int i = 0; i < 10; i++)
{
ThreadList.Add(new Thread(new ParameterizedThreadStart(HelloThread)));
ThreadList[i].Start(DateTime.Now);
}
foreach (Thread requestThread in ThreadList)
{
requestThread.Join();
}
Console.WriteLine(threadCount);
}
}
}
3 thoughts on “C# thread 共用變數(C# thread lock)”
此範例為無限等待型
C# THREAD 非無限等待型的 LOCK ~ Monitor.TryEnter Method
https://docs.microsoft.com/en-us/dotnet/api/system.threading.monitor.tryenter?view=netframework-4.8
var lockObj = new Object();
int timeout = 500;
bool lockTaken = false;
try {
Monitor.TryEnter(lockObj, timeout, ref lockTaken);
if (lockTaken) {
// The critical section.
}
else {
// The lock was not acquired.
}
}
finally {
// Ensure that the lock is released.
if (lockTaken) {
Monitor.Exit(lockObj);
}
}
C# THREAD 共用變數(C# THREAD LOCK) 執行序鎖