Fra*_*tha 6 c# remoting task-parallel-library
我们有一个基于.NET Remoting的传统应用程序.我们的客户端客户端库目前仅支持同步操作.我想用基于TPL的async Task<>方法添加异步操作.
作为概念证明,我已经基于这些指令的修改版本设置了基本的远程服务器/客户端解决方案.
我还发现这篇文章描述了如何将基于APM的异步操作转换为基于TPL的异步任务(使用Task.Factory.FromAsync)
我不确定的是我是否被迫在其中指定回调函数.BeginInvoke()并且还指定了.EndInvoke().如果两者都是必需的,回调函数与之间的区别究竟是什么.EndInvoke().如果只需要一个,我应该使用哪一个来返回值,并确保我没有内存泄漏.
这是我当前的代码,我没有将回调传递给.BeginInvoke():
public class Client : MarshalByRefObject
{
private IServiceClass service;
public delegate double TimeConsumingCallDelegate();
public void Configure()
{
RemotingConfiguration.Configure("client.exe.config", false);
var wellKnownClientTypeEntry = RemotingConfiguration.GetRegisteredWellKnownClientTypes()
.Single(wct => wct.ObjectType.Equals(typeof(IServiceClass)));
this.service = Activator.GetObject(typeof(IServiceClass), wellKnownClientTypeEntry.ObjectUrl) as IServiceClass;
}
public async Task<double> RemoteTimeConsumingRemoteCall()
{
var timeConsumingCallDelegate = new TimeConsumingCallDelegate(service.TimeConsumingRemoteCall);
return await Task.Factory.FromAsync
(
timeConsumingCallDelegate.BeginInvoke(null, null),
timeConsumingCallDelegate.EndInvoke
);
}
public async Task RunAsync()
{
var result = await RemoteTimeConsumingRemoteCall();
Console.WriteLine($"Result of TPL remote call: {result} {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");
}
}
public class Program
{
public static async Task Main(string[] Args)
{
Client clientApp = new Client();
clientApp.Configure();
await clientApp.RunAsync();
Console.WriteLine("Press any key to continue...");
Console.ReadKey(false);
}
}
Run Code Online (Sandbox Code Playgroud)
回调函数与 之间的区别.EndInvoke()在于回调将在线程池中的任意线程上执行。如果您必须确保从与调用 BeginInvoke 的线程相同的线程上获取读取结果,则不应使用回调,而应轮询 IAsyncResult 对象并.EndInvoke()在操作完成时调用。
如果您.EndInvoke()在 后立即调用.Beginnvoke(),则会阻塞线程直到操作完成。这会起作用,但扩展性很差。
所以,你所做的似乎没问题!