[英]Instantiate and Call WCF service Asynchronously
我有一个用于实例化WCF服务并执行操作的帮助程序方法。 这对于同步调用非常有用,并且确实减少了我的主类中的代码。 但是,我试图在对服务的异步调用上实现相同的方法,并且在语法上遇到麻烦。
这是我正在使用的辅助方法:
public static void Use(Action<T> action)
{
ChannelFactory<T> Factory = new ChannelFactory<T>("*");
ClientCredentials Credentials = new ClientCredentials();
Credentials.UserName.UserName = USER_NAME;
Credentials.UserName.Password = PASSWORD;
Factory.Endpoint.EndpointBehaviors.Remove(typeof(ClientCredentials));
Factory.Endpoint.EndpointBehaviors.Add(Credentials);
T Client = Factory.CreateChannel();
bool Success = false;
try
{
action(Client);
((IClientChannel)Client).Close();
Factory.Close();
Success = true;
}
catch (CommunicationException cex)
{
Log.Error(cex.Message, cex);
}
catch (TimeoutException tex)
{
Log.Error(tex.Message, tex);
}
finally
{
if (!Success)
{
((IClientChannel)Client).Abort();
Factory.Abort();
}
}
}
这是我从计时器经过的事件对helper方法进行的同步调用:
async void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
Service<IVehicleService>.Use(client =>
{
Vehicles = client.GetAllVehicles(new GetAllVehiclesRequest()).vehicleList;
});
await UpdateVehicleStatuses();
}
这是调用GetVehicleStatus方法的地方:
private async Task UpdateVehicleStatuses()
{
// Can the call to GetVehicleStatus be turned into a lambda expression utilizing the helper method?
IEnumerable<Task<VehicleStatus>> StatusQuery = from s in Vehicles
select GetVehicleStatus(s.ClientVehicleId);
List<Task<VehicleStatus>> StatusTasks = StatusQuery.ToList();
...
}
这是GetVehicleStatus方法的当前正文:
private async Task<VehicleStatus> GetVehicleStatus(string clientVehicleID)
{
// Can this method be modified to use the helper method?
GetStatusResponse Status = await VehicleClient.GetStatusByClientIdAsync(clientVehicleID);
return Status.vehicleStatus;
}
我想将相同的主体从同步调用应用到异步调用,这样我就不必在主类中初始化服务,并且可以在那里封装所有错误处理。 尝试将GetVehicleStatus方法转换为UpdateVehicleStatuses方法中的lambda表达式时,语法出现问题。 我也尝试过修改GetVehicleStatus方法以利用helper方法而没有运气。 我想念什么?
谢谢!
您将需要异步的助手方法版本:
public static async Task UseAsync(Func<T, Task> action)
{
...
try
{
await action(Client);
...
}
此外,如果您需要支持返回值,那么您将需要另一个重载:
public static async Task<TResult> UseAsync(Func<TClient, Task<TResult>> action)
{
...
TResult result;
try
{
result = await action(Client);
...
return result;
}
然后,您可以像这样使用它:
private async Task<VehicleStatus> GetVehicleStatusAsync(string clientVehicleID)
{
GetStatusResponse Status = await UseAsync(client => client.GetStatusByClientIdAsync(clientVehicleID));
return Status.vehicleStatus;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.