【问题标题】:Understanding AsynkCallBack and IAsyncResult了解 AsyncCallBack 和 IAsyncResult
【发布时间】:2017-11-23 04:07:19
【问题描述】:

我继承了一些广泛使用 AsyncCallback / IAsyncResult 的旧 .NET 2.0 代码,我试图更好地了解它的工作原理。 例如,我正在使用我在这里找到的一些代码:

static void TestCallbackAPM()
    {   
        byte[] bytesToRead = new byte[100] //Just read first 100 bytes
        string filename = "Moq.dll";
        FileStream strm = new FileStream(filename,
            FileMode.Open, FileAccess.Read, FileShare.Read, 1024,
            FileOptions.Asynchronous);

        // Make the asynchronous call
        IAsyncResult result = strm.BeginRead(buffer, 0, buffer.Length,
            new AsyncCallback(CompleteRead), strm);

    }
static void CompleteRead(IAsyncResult result)
    {
        Console.WriteLine("Read Completed");

        FileStream strm = (FileStream)result.AsyncState;

        // Finished, so we can call EndRead and it will return without blocking
        int numBytes = strm.EndRead(result);

        // Don't forget to close the stream
        strm.Close();

        Console.WriteLine("Read {0} Bytes", numBytes);
        Console.WriteLine(BitConverter.ToString(buffer));

我不明白 IAsyncResult 结果 是如何传回 CompleteRead 方法的。要创建 IAsyncResult 结果,我需要将 CompleteRead 委托传递给它,但是它以某种方式调用 CompleteRead 方法,将自身作为参数传递给它?那是一些《盗梦空间》的东西。 这是如何运作的?或者它只是一些 .NET 引擎盖下的魔法?

【问题讨论】:

    标签: c# .net asynchronous callback


    【解决方案1】:

    不要让变量名让您感到困惑。这是电话:

    // Make the asynchronous call
    IAsyncResult result = strm.BeginRead(buffer, 0, buffer.Length,
                new AsyncCallback(CompleteRead), strm);
    

    这是你的代表。您的委托中名为result 的参数与上述result 变量无关。他们只是碰巧有相同的名字。这个result 实际上是上面的最后一个参数strm。这就是为什么您实际上可以将其转换为 FileStream,如下所示:

    static void CompleteRead(IAsyncResult result)
    {
        // ... code
        FileStream strm = (FileStream)result.AsyncState;
        // ... code
    }
    

    【讨论】:

    • 啊!这是有道理的,所以基本上您可以将任何对象作为 IAsyncResult 传递并稍后在委托中将其强制转换?
    猜你喜欢
    • 1970-01-01
    • 2011-08-03
    • 2013-01-06
    • 1970-01-01
    • 2010-10-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-18
    • 1970-01-01
    相关资源
    最近更新 更多