
System.Runtime.ComplierService命名空间包含的一些属性将影响CLR在运行时的行为。
MethodImplAttribute的一个构造函数把MethodImplOption枚举作为其参数。
MethodImplOptions枚举有一个字段Synchronized,它指定在任一时刻只允许一个线程访问这个方法。
但它不处理静态字段和方法的同步。如果必须同步特定代码块,它也不起作用。同步整个对象是对轻松使用必须付出的代价。
示例展示了使用MethodImplAttribute的效果与没有使用同步线程时不一样。
using System;
using System.Threading;
using System.Runtime.CompilerServices;
namespace thread
{
public class MethodImpl
{
class MI
{
//This attribute locks the method for use
//by one and only one thread at a time.
[MethodImpl(MethodImplOptions.Synchronized)]
public void doSomeWorkSync()
{
Console.WriteLine("doSomeWorkSync()--Lock held by Thread" + Thread.CurrentThread.GetHashCode());
Thread.Sleep(5 * 1000);
Console.WriteLine("doSomeWorkSync() --Lock released by Thread" + Thread.CurrentThread.GetHashCode());
}
//This is a non synchronized method
public void doSomeWorkNoSync()
{
Console.WriteLine("doSomeWorkNoSync()--Entered Thread is" + Thread.CurrentThread.GetHashCode());
Thread.Sleep(5 * 1000);
Console.WriteLine("doSomeWorkNoSync()" + Thread.CurrentThread.GetHashCode());
}
[STAThread]
public static void Main(string[] args)
{
MI m = new MI();
//Delegate for Non-Synchronous operation
ThreadStart tsNoSyncDelegate = new ThreadStart(m.doSomeWorkNoSync);
//Delegate for Synchronous operation
ThreadStart tsSyncDelegate =
new ThreadStart(m.doSomeWorkSync);
Thread t1=new Thread(tsNoSyncDelegate);
Thread t2=new Thread(tsNoSyncDelegate);
t1.Start();
t2.Start();
Thread t3 = new Thread(tsSyncDelegate);
Thread t4 = new Thread(tsSyncDelegate);
t3.Start();
t4.Start();
}

}
}
}
本文探讨了System.Runtime.CompilerServices命名空间中的MethodImplAttribute及其Synchronized选项如何实现方法级别的线程同步。通过示例代码展示了同步与非同步方法在多线程环境下的行为差异。

2243

被折叠的 条评论
为什么被折叠?



