异步实例化和调用WCF服务

时间:2014-11-13 15:17:43

标签: c# linq wcf asynchronous async-await

我有一个帮助方法,用于实例化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();
            }
        }
    }

这是我从计时器已用事件中对辅助方法进行的同步调用:

    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方法以利用辅助方法而没有运气。我错过了什么?

谢谢!

1 个答案:

答案 0 :(得分:3)

您需要辅助方法的异步版本:

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;
}