【发布时间】: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