C# thread 共用變數(C# thread lock)

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)

  1. 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);
    }
    }

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *