同步类MethodImplAttribute的使用


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();
       }

       

            
        }

      
    }

}

 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值