我继承了一些旧的.NET 2.0代码,这些代码广泛使用了AsyncCallback / IAsyncResult,我试图更好地理解它是如何工作的。例如,我使用了一些我在这里找到的代码:
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?
发布于 2017-11-23 04:24:58
不要让变量名迷惑您。这是一个号召:
// 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
}https://stackoverflow.com/questions/47447404
复制相似问题