【发布时间】:2018-11-05 12:45:52
【问题描述】:
我们有一个基于 .NET Remoting 的旧版应用程序。我们的客户端客户端库目前仅支持同步操作。我想使用基于 TPL 的 async Task<> 方法添加异步操作。
作为概念证明,我已经基于these instructions 的修改版本建立了一个基本的远程服务器/客户端解决方案。
我还找到了this article,它描述了如何将基于 APM 的异步操作转换为基于 TPL 的异步任务(使用 Task.Factory.FromAsync)
我不确定的是我是否必须在.BeginInvoke() 中指定回调函数并指定.EndInvoke()。如果两者都需要,回调函数和.EndInvoke()之间究竟有什么区别。如果只需要一个,我应该使用哪一个来返回值并确保我have no memory leaks。
这是我当前的代码,我没有将回调传递给.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);
}
}
【问题讨论】:
标签: c# task-parallel-library remoting