I'm using Remoting to perform some IPC communic开发者_JAVA技巧ation, and have the following question:
When I invoke delegates to gather data server-side, it is possible to have an event fired on the client when an IAsyncResult is gathered?
The following code is in VC++, but .net code is .net code.
GetFileTextDelegate ^svd = gcnew GetFileTextDelegate(obj, &BaseRemoteObject::GetFileText);
IAsyncResult ^arValSet = svd->BeginInvoke(nullptr, nullptr);
String ^result = svd->EndInvoke(arValSet);
In this example, the last line of code will just lock the current thread until the Invoke is completed. Is it possible to just subsbribe to a "IAsyncResult_Completed" event, or something similar?
Thanks
Yes, there's a good example on MSDN of using the AsyncCallback
delegate to do this.
The easiest way to do this, is that use BeginInvoke
on a delegate and pass it an instance of an AsynCallback
delegate to invoke when the operation completes.
In C# (which I'm more familiar with than managed C++) you would basically write:
// when the async operation completes, YourCallBackMethod will be run
AsyncCallback callback = new AsynCallback( YourCallBackMethod );
callAsynchronously.BeginInvoke( callback, null );
In your callback method you must call EndInvoke()
on the delegate which you ran asynchronously. The easiest way to do this is to use the supplied IAsyncResult
.
You should be able to pass a delegate (AsyncCallBack) to your BeginInvoke, which will execute when the async method has finished executing.
Here is a simple, but straightforward example:
using System;
using System.Threading;
using System.Runtime.Remoting.Messaging;
class MainClass
{
delegate int MyDelegate(string s);
static void Main(string[] args)
{
MyDelegate X = new MyDelegate(DoSomething);
AsyncCallback cb = new AsyncCallback(DoSomething2);
IAsyncResult ar = X.BeginInvoke("Hello", cb, null);
Console.WriteLine("Press any key to continue");
Console.ReadLine();
}
static int DoSomething(string s)
{
Console.WriteLine("doooooooooooooooo");
return 0;
}
static void DoSomething2(IAsyncResult ar)
{
MyDelegate X = (MyDelegate)((AsyncResult)ar).AsyncDelegate;
X.EndInvoke(ar);
}
}
精彩评论