[英]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.