首页 > 代码库 > C# 语法 ( 框架自带委托和异步 )

C# 语法 ( 框架自带委托和异步 )

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace 异步线程
{
  class AsyncHronous
  {
    private int i = 0;

    public void Show()
    {
      for (int i = 0; i < 5; i++)
      {
        //系统自带的委托(有参数无返回值,有参数有返回值)
        Action action = new Action(Index);//回调函数(异步执行委托的第二个参数)
        AsyncCallback async = new AsyncCallback((x) => Console.WriteLine("我是回调值{0}", x.AsyncState));

        //异步执行委托(回调函数,回调函数的参数)
        action.BeginInvoke(async, 12);  
      }
    }

    public void Index()
    {
      Console.WriteLine("当前线程id是{0}", Thread.CurrentThread.ManagedThreadId);
      Thread.Sleep(1000);
      Console.WriteLine("我是第{0}名", i);
      i++;
    }
  }
}

 

<!--自带的委托-->

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace λ表达式
{
  public class LambdaA
  {
    public void show()
    {
      //有参数无返回值的系统自带委托(最多支持16个参数)
      Action<int, string, bool> action = (x, y, z) => Console.WriteLine(x + y + z);
      action(1, "2", true);

      //有参数有返回值的系统自带委托(最多支持16个参数和一个返回值)
      Func<int, int, int> func = (x, y) => x + y;
      Console.WriteLine(func(2, 3));
    }
  }
}

 

C# 语法 ( 框架自带委托和异步 )