并发学习之:Synchronization进行粗粒度线程同步的例子

一个使用Synchronization进行粗粒度线程同步的例子。(注意,Synchronization特性和ContextBoundObject必须同时使用,否则无效)

这个例子很简单,2个Task对象,分别调用兽族农民的WorkWork和GugiGugi方法。GugiGugi内部有着3秒的停顿,用来观察输出结果。运行之后,很明显的可以看到,在某一个线程执行GugiGugi的时候,另一个线程在等待。


using System;
using System.Runtime.Remoting.Contexts;
using System.Threading;
using System.Threading.Tasks;

namespace SyncContextTest
{
    [Synchronization()]
    class Orc : ContextBoundObject
    {
        public void WorkWork()
        {
            Console.WriteLine(DateTime.Now + " WorkWork - ThreadId: " + Thread.CurrentThread.ManagedThreadId);
        }

        public void GugiGugi()
        {
            Task.Delay(3000).Wait();
            Console.WriteLine(DateTime.Now + " GugiGugi - ThreadId: " + Thread.CurrentThread.ManagedThreadId);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Orc sharedOrc = new Orc();

            Task task1 = Task.Factory.StartNew(() =>
            {
                for (int i = 0; i < 10; ++i)
                {
                    sharedOrc.WorkWork();
                }
            });

            Task task2 = Task.Factory.StartNew(() =>
            {
                for (int i = 0; i < 10; ++i)
                {
                    sharedOrc.GugiGugi();
                }
            });

            Task.WaitAll(task1, task2);
        }
    }
}


输出:

1/5/2013 5:02:04 PM GugiGugi - ThreadId: 5
1/5/2013 5:02:04 PM WorkWork - ThreadId: 4
1/5/2013 5:02:07 PM GugiGugi - ThreadId: 5
1/5/2013 5:02:07 PM WorkWork - ThreadId: 4
1/5/2013 5:02:10 PM GugiGugi - ThreadId: 5
1/5/2013 5:02:10 PM WorkWork - ThreadId: 4
1/5/2013 5:02:13 PM GugiGugi - ThreadId: 5
1/5/2013 5:02:13 PM WorkWork - ThreadId: 4
1/5/2013 5:02:16 PM GugiGugi - ThreadId: 5
1/5/2013 5:02:16 PM WorkWork - ThreadId: 4
1/5/2013 5:02:19 PM GugiGugi - ThreadId: 5
1/5/2013 5:02:19 PM WorkWork - ThreadId: 4
1/5/2013 5:02:22 PM GugiGugi - ThreadId: 5
1/5/2013 5:02:22 PM WorkWork - ThreadId: 4
1/5/2013 5:02:25 PM GugiGugi - ThreadId: 5
1/5/2013 5:02:25 PM WorkWork - ThreadId: 4
1/5/2013 5:02:28 PM GugiGugi - ThreadId: 5
1/5/2013 5:02:28 PM WorkWork - ThreadId: 4
1/5/2013 5:02:31 PM GugiGugi - ThreadId: 5
1/5/2013 5:02:31 PM WorkWork - ThreadId: 4
Press any key to continue . . .


你可能感兴趣的:(并发学习之:Synchronization进行粗粒度线程同步的例子)