Consider the following function:
static void Main(string[] args)
{
FileStream fs = new FileStream("e:\\temp.txt", FileMode.Open);
int size = (int)fs.Length;
byte[] data = new byte[size];
IAsyncResult result = fs.BeginRead(data, 0, size, new AsyncCallback(Callback), fs);
Console.ReadLine();
}
Question1: If I put a breakpoint on BeginRead line, and run the program in debug mode, I get the following error:
An unhandled exception of type 'System.AccessViolationException' occurred in MyApp.exe.
However, if I put the breakpoint on the ReadLine line and do the same the error doesn't occur. I believe passing the FileStream instance as the last parameter to the BeginRead function causes the problem, however, I've no idea what is happening there.
---UPDATE1: You might ask why I'm trying to pass "fs" to the callback. Yes, I can hold it as a member variable however what if I was going to read multiple files asynchronously? That way, holding an array (or list) of file streams would be irrational.
Question2: AFAIK, IAsyncResult is defined as follows:
[ComVisible(true)]
public interface IAsyncResult
{
object AsyncState { get; }
WaitHandle AsyncWaitHandle { get; }
bool CompletedSynchronously { get; }
bool IsCompleted { get; }
}
However, when tracing the code, I've noticed other members on IAsyncResult:
How's this possible? The IAsyncResult is obviously implemented by ReadWriteTask class (in this case), however, I don't get where those other properties come from.
---Update 2: I tried to mimic the same using the following code:
public interface IMyInterface
{
int Prop1 { get; }
}
public class Impl : IMyInterface
{
public int Prop1 { get { return 101; } }
public int Prop2 { get { return 202; } }
}
public class MyClass
{
public IMyInterface GetMyInterface()
{
Impl impl = new Impl();
return impl;
}
}
And to invoke the method, I just instantiate a MyClass and call the GetMyInterface method as follows:
MyClass c = new MyClass();
IMyInterface my = c.GetMyInterface();
However, when I watch the my variable in Quickwatch, I see the non-flattened result which is totally OK with me. However, this is not the same case for IAsyncResult / ReadWriteTask. What's the difference?