我需要连接到服务器并收集数据进行处理。下面是我的核心类,它负责遍历所有服务器并尝试将它们连接以进行处理。
public class CoreDataProcessingEngine : ICoreDataProcessingEngine
{
private readonly COMLib.ServerGateway _aServerGw;
private COMLib.ServerErrorInfo _aServerErrorInfo;
Public CoreDataProcessingEngine()
{
_aServerGw = new COMLib.ServerGateway();
_aServerErrorInfo = new COMLib.ServerErrorInfo();
}
//When service starts, I am collecting all the server details from config and trying to connect ONE BY ONE.
public async Task Start()
{
List<Server> servers = ConfigurationManager.GetSection("servers") as List<Server>;
foreach (var serverdetails in servers)
{
var data = Task.Run(() => ConnectToServer(serverdetails ));
}
}
}
这是我的ConnectToServer
方法
private async void ConnectToGateway(ServerDetails serverdetails )
{
await _aServerGw.connectToServerByName(serverdetails.serveraddress);
}
我将connectToServerByName
方法扩展如下,该方法在单独的静态类中。
public static class ComLibraryExtensions
{
public static Task connectToServerByName(this ProxyGW @this, string serveraddress)
{
var tcs = new TaskCompletionSource<object>();
Action onSuccess = null;
Action<int> onFailed = null;
onSuccess = () =>
{
@this.onConnectSucceeded -= HandleManager_OnConnectSucceeded;
@this.onConnectFailed -= HandleManager_OnConnectFailed;
tcs.TrySetResult(null);
};
onFailed = hr =>
{
@this.onConnectSucceeded -= HandleManager_OnConnectSucceeded;
@this.onConnectFailed -= HandleManager_OnConnectFailed;
tcs.TrySetException(Marshal.GetExceptionForHR(hr));
};
@this.onConnectSucceeded += HandleManager_OnConnectSucceeded;
@this.onConnectFailed += HandleManager_OnConnectFailed;
@this.connectToGatewayByNameEx(serveraddress);
return tcs.Task;
}
private static void HandleManager_OnConnectFailed(int hr)
{
//How do I get access to dependent objects here?
//Like ILogger ??
_logger.Information(hr);
}
private static void HandleManager_OnConnectSucceeded()
{
//How do I get access @this??
@this.enableNotifications(true);//fails , it says @this does not exists
}
}
问题是:
_aServerGw
事件中如何访问HandleManager_OnConnectSucceeded
,因为我想基于success
事件设置一些属性。