zoukankan      html  css  js  c++  java
  • 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();

    }

    }

     

  • 相关阅读:
    51 Nod 1035 最长的循环节 (此题还不是很懂,日后再看)
    51 Nod 1101 换零钱(动态规划好题)
    51 Nod 1101 换零钱(动态规划好题)
    51 Nod 1163 最高的奖励
    51 Nod1042 数字0到9的数量
    51 Nod 1629 B君的圆锥
    iterrows(), iteritems(), itertuples()对dataframe进行遍历
    pandas计数 value_counts()
    scikit_learn逻辑回归类库
    Python中的深拷贝和浅拷贝
  • 原文地址:https://www.cnblogs.com/foundation/p/1511444.html
Copyright © 2011-2022 走看看