多线程的两个常用demo

异步调用的四种方式

 

using  System;
using  System.Threading;

namespace  ThreadDemo
{
    
public class YibuSelf
    
{
        
public delegate void MyDelegate();
        
public static MyDelegate dele;

        
public static void Main()
        
{
            
同步方式
            
            dele 
= new MyDelegate( Test );
    
            
回调方式

            
轮询方式

            
调用End方法

            
WaitHandle

            
// 执行线程中其他内容
            Console.WriteLine("线程的其余部分执行");

            Console.Read();
        }


        
public static void Test()
        
{
            
forint i=0; i<10; i++)
            
{
                Console.Write(
"+");
                Thread.Sleep(
200);
            }

        }


        
public static void MyCallback( IAsyncResult ar )
        
{
            dele.EndInvoke( ar );

            Console.WriteLine();
            Console.WriteLine(
"异步操作结束.");
        }

    }

}

 在多线程环境中保护状态和数据

 

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

using  System.Runtime.CompilerServices;

namespace  ThreadDemo
{
    
//[Synchronization]
    public class Synch_Example : ContextBoundObject
    
{
        
static int sCount = 0;    // 静态字段
        int iCount = 0;            // 实例字段

        
// 同一时刻只有一个线程可以执行实例方法

        
事例方法
        
        
静态方法    
    }


    
class Example_Synch
    
{
        
public static void Main()
        
{
            Synch_Example se1 
= new Synch_Example();

            
实例方法线程
            
            Thread.Sleep( 
1000 );

            
静态方法线程

            Console.Read();
        }

    }

}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值