System.IAsyncResult 接口

System.IAsyncResult 接口

 

System.IAsyncResult接口编写异步方法中常用的一个接口,我在WF的InvokeMethod , WorkflowInvoker 例子中也用到了这个接口.由于有些朋友对System.IAsyncResult接口不了解,我特别写了一个实现System.IAsyncResult 接口的例子

 

public class myAsyncResult : System.IAsyncResult

{

 

public object AsyncState

{

get;

set;

}

 

System.Threading.WaitHandle asyncWaitHandle = new AutoResetEvent(false);

public System.Threading.WaitHandle AsyncWaitHandle

{

get { return asyncWaitHandle; }

}

 

public bool CompletedSynchronously

{

get;

set;

}

 

public bool IsCompleted

{

get;

set;

}

 

int _myValue;

public int myValue

{

set

{ _myValue = value; }

get

{

// if (IsCompleted)

{

return _myValue;

}

 

}

}

}

class myClass

{

AsyncCallback asyncCallback;

 

myAsyncResult asyncResult;

 

public myClass()

{

asyncCallback = new AsyncCallback(callback);

asyncResult = new myAsyncResult();

}

void callback(IAsyncResult asyncResult)

{

myAsyncResult temp = asyncResult as myAsyncResult;

 

((AutoResetEvent)temp.AsyncWaitHandle).Set();

}

 

public myAsyncResult myAsyncMethod(int value, object asyncState)

{

 

Console.WriteLine("run myAsyncMethod");

 

this.asyncResult.AsyncState = asyncState;

this.asyncResult.myValue = value;

 

Thread t = new Thread(new ThreadStart(myThread));

t.Start();

 

return this.asyncResult;

}

 

void myThread()

{

Console.WriteLine("begin myThread");

for (int i = 0; i < 5; i++)

{

Console.WriteLine(i);

asyncResult.myValue = asyncResult.myValue + i;

Thread.Sleep(500);

}

Console.WriteLine("end myThread");

 

asyncCallback(this.asyncResult);

}

 

 

}

class Program

{

static void Main(string[] args)

{

myClass obj = new myClass();

 

myAsyncResult r = obj.myAsyncMethod(100, null);

 

r.AsyncWaitHandle.WaitOne();

 

System.Console.WriteLine(r.myValue);

 

System.Console.WriteLine("完成");

 

System.Console.Read();

}

}

 

posted @   WXWinter(冬)  阅读(3454)  评论(1编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
点击右上角即可分享
微信分享提示