Dumping the Delegation Type in JScript.NET
I'm trying to do async IO using BeginRead () in JScript.NET, but I can't seem to get the callback to work correctly.
Here is the code:
function readFileAsync() {
var fs : FileStream = new FileStream( 'test.txt', FileMode.Open, FileAccess.Read );
var result : IAsyncResult = fs.BeginRead( new byte[8], 0, 8, readFileCallback ), fs );
Thread.Sleep( Timeout.Infinite );
}
var readFileCallback = function( result : IAsyncResult ) : void {
print( 'ListenerCallback():' );
}
An exception to this is throwing failure:
Unhandled Exception: System.InvalidCastException: Unable to cast object of type 'Microsoft.JScript.Closure' to type 'System.AsyncCallback'.
at JScript 0.readFileAsync(Object this, VsaEngine vsa Engine)
at JScript 0.Global Code()
at JScript Main.Main(String[] )
I've tried to do an explicit cast to both AsyncCallback and the underlying MulticastDelegate and Delegate types to no avail.
Delegates are supposed to be created automatically, eliminating the need to create a new AsyncCallback explicitly, for example:
BeginRead( ... new AsyncDelegate( readFileCallback), object );
And in fact, if you try to create a delegate explicitly, the compiler throws an error. I am missing something here.
a source to share
The problem stems from the fact that internally the delegate is created with
Delegate.CreateDelegate( Type, Object, String )
where Type is the type of the delegate to create, Object is the instance on which the method will be invoked, and String is the name of the method. For this to work, the function must be an instance method, so we must define the class as such:
class AsyncFileReader
{
function readFileAsync() {
var fs : FileStream = new FileStream(
'test.txt', FileMode.Open, FileAccess.Read
);
var result : IAsyncResult = fs.BeginRead(
new byte[8], 0, 8, ListenerCallback, fs
);
// Sleep just for testing
Thread.Sleep( Timeout.Infinite );
}
function ListenerCallback( result : IAsyncResult ) : void {
print( 'ListenerCallback():' );
}
} // class
Since the callback can now bind to the AsyncFileReader instance at runtime, the conversion will be done. The error posted above was most likely one of my attempts at explicit casting, which is not what happens during conversion.
a source to share