BeginInvoke的用法

using System;
using System.Threading;
class MyTest
{
	delegate bool deleTest(string a,string b);
	static void Main(string[] args)
	{
		deleTest mytest = new deleTest(Test);
		IAsyncResult testRecult = mytest.BeginInvoke("a", "b", null, null);

		Write();
		
		Console.WriteLine(mytest.EndInvoke(testRecult));
	}
	public static bool Test(string s1, string s2)
	{
		Thread.Sleep(3000);
		Console.WriteLine("InTest");
		if (s1 == s2)
			return true;
		return false;
	}

	public static void Write()
	{
		Console.WriteLine("InWrite");
	}
}
/*
运行结果:

InWrite
InTest
False
*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
BeginInvoke是委托的一个异步调用方法,它可以在新的线程中执行委托所指向的方法,而不会阻塞当前线程。BeginInvoke方法返回一个IAsyncResult接口,可以通过该接口的AsyncWaitHandle属性来等待异步操作完成。 使用BeginInvoke方法的一般步骤如下: 1. 定义一个委托类型; 2. 创建委托实例,并将要执行的方法作为参数传递给委托构造函数; 3. 调用委托实例的BeginInvoke方法,并传递需要异步执行的参数; 4. 在需要等待异步操作完成的地方,调用IAsyncResult接口的AsyncWaitHandle属性的WaitOne方法等待异步操作完成; 5. 调用委托实例的EndInvoke方法获取异步操作的返回值。 示例代码如下: ``` public delegate int MyDelegate(int a, int b); public class MyClass { public int Add(int a, int b) { Console.WriteLine("Add方法开始执行,当前线程ID为:" + Thread.CurrentThread.ManagedThreadId); Thread.Sleep(3000); Console.WriteLine("Add方法执行完成"); return a + b; } } class Program { static void Main(string[] args) { Console.WriteLine("Main方法开始执行,当前线程ID为:" + Thread.CurrentThread.ManagedThreadId); MyClass myClass = new MyClass(); MyDelegate myDelegate = new MyDelegate(myClass.Add); IAsyncResult asyncResult = myDelegate.BeginInvoke(1, 2, null, null); Console.WriteLine("Main方法继续执行,当前线程ID为:" + Thread.CurrentThread.ManagedThreadId); asyncResult.AsyncWaitHandle.WaitOne(); int result = myDelegate.EndInvoke(asyncResult); Console.WriteLine("异步操作返回值为:" + result); Console.ReadKey(); } } ``` 输出结果如下: ``` Main方法开始执行,当前线程ID为:1 Main方法继续执行,当前线程ID为:1 Add方法开始执行,当前线程ID为:3 Add方法执行完成 异步操作返回值为:3 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

__简言

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值