繁体   English   中英

如何在c#中调用Web服务方法

[英]How to call a web service method in c#

我想知道如何安全地调用WCF Web服务方法。 这两种方法都可接受/等同吗? 有没有更好的办法?

第一种方式:

public Thing GetThing()
{
    using (var client = new WebServicesClient())
    {
        var thing = client.GetThing();
        return thing;
    }
}

第二种方式:

public Thing GetThing()
{
    WebServicesClient client = null;
    try
    {
        client = new WebServicesClient();
        var thing = client.GetThing();
        return thing;
    }
    finally
    {
        if (client != null)
        {
            client.Close();
        }
    }
}

我想确保客户端正确关闭并处理掉。

谢谢

建议不要使用using (无双关语),因为即使是Dispose()也会抛出异常。

这是我们使用的几种扩展方法:

using System;
using System.ServiceModel;

public static class CommunicationObjectExtensions
{
    public static void SafeClose(this ICommunicationObject communicationObject)
    {
        if(communicationObject.State != CommunicationState.Opened)
            return;

        try
        {
            communicationObject.Close();
        }
        catch(CommunicationException ex)
        {
            communicationObject.Abort();
        }
        catch(TimeoutException ex)
        {
            communicationObject.Abort();
        }
        catch(Exception ex)
        {
            communicationObject.Abort();
            throw;
        }
    }

    public static TResult SafeExecute<TServiceClient, TResult>(this TServiceClient communicationObject, 
        Func<TServiceClient, TResult> serviceAction)
        where TServiceClient : ICommunicationObject
    {
        try
        {
            var result = serviceAction.Invoke(communicationObject);
            return result;
        } // try

        finally
        {
            communicationObject.SafeClose();
        } // finally
    }
}

有了这两个:

var client = new WebServicesClient();
return client.SafeExecute(c => c.GetThing());

第二种方法稍微好一点,因为您正在处理可能引发异常的事实。 如果你陷入困境并且至少记录了特定的异常,那就更好了。

但是,此代码将阻止,直到GetThing返回。 如果这是一个快速操作,那么它可能不是一个问题,但另一种更好的方法是创建一个异步方法来获取数据。 这会引发一个事件以指示完成,并且您订阅该事件以更新UI(或者您需要做什么)。

不完全的:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM