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 @ 2009-06-26 10:19  WXWinter(冬)  阅读(3450)  评论(1编辑  收藏  举报