(二)线程--通过委托异步调用方法(示例下载)

本文介绍了一个使用C#实现的简单线程示例,演示了如何通过委托调用方法及利用AsyncResult对象来检查线程状态。代码示例中包含了两种调用方式:一种是直接调用对象实例的方法,另一种则是通过异步调用静态方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

2005年11月30日 23:06:00

(一).描述
先运行个简单的线程示例,认识一下线程
通过委托调用方法,以及使用AsyncResult判断线程的状态

(二).代码
using System;
using System.Threading;
using System.Runtime.Remoting.Messaging;

namespace 通过委托异步调用方法
{
//委托声明(函数签名)
delegate string MyMethodDelegate();

class MyClass
{
//要调用的动态方法
public string MyMethod1()
{
return "Hello Word1";
}

//要调用的静态方法
public static string MyMethod2()
{
return "Hello Word2";
}
}
class Class1
{
/// >summary<
/// 应用程序的主入口点。
/// >/summary<
[STAThread]
static void Main(string[] args)
{
MyClass myClass = new MyClass();

//方式1: 声明委托,调用MyMethod1
MyMethodDelegate d = new MyMethodDelegate(myClass.MyMethod1);
string strEnd = d();
Console.WriteLine(strEnd);

//方式2: 声明委托,调用MyMethod2 (使用AsyncResult对象调用)
d = new MyMethodDelegate(MyClass.MyMethod2); //定义一个委托可以供多个方法使用
AsyncResult myResult; //此类封闭异步委托异步调用的结果,通过AsyncResult得到结果.
myResult = (AsyncResult)d.BeginInvoke(null,null); //开始调用
while(!myResult.IsCompleted) //判断线程是否执行完成
{
Console.WriteLine("正在异步执行MyMethod2 .....");
}
Console.WriteLine("方法MyMethod2执行完成!");
strEnd = d.EndInvoke(myResult); //等待委托调用的方法完成,并返回结果
Console.WriteLine(strEnd);
Console.Read();
}
}
}


本示例代码已经测试,能够正常运行!

(三).示例下载
http://www.cnblogs.com/Files/ChengKing/ThreadExample.rar



Trackback: http://tb.blog.youkuaiyun.com/TrackBack.aspx?PostId=540637


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值