using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Runtime.CompilerServices; namespace TestMethodSynchronized { class SyncHelper { static int cnt = 0; [MethodImpl(MethodImplOptions.Synchronized)] public static void Execute(object state) { int t = cnt; Console.WriteLine("ThreadId:{2,-5}, Sate:{1},Excute at {0},计时器:{3}", DateTime.Now, state.ToString(), Thread.CurrentThread.ManagedThreadId, t); Thread.Sleep(500); ++t; cnt = t; } } class Program { static void Main(string[] args) { for (int i = 0; i < 10; i++) { ThreadPool.QueueUserWorkItem(SyncHelper.Execute,i); } Console.WriteLine("done."); Console.ReadKey(); } } }
C#多线程方法同步
时间: 2024-10-29 19:12:20