3

ASP.NET MVCアプリでWCFを使用しており、各メソッドにtry-catch-finallyブロックが含まれています。WCF呼び出しを正しく閉じる/中止するかどうか疑問に思っています。「using」ステートメントはWCF呼び出しには適していないことを私は知っています。

これがサンプルの方法です

public int GetInvalidOrdersCount()
{
    OrderServiceClient svc = new OrderServiceClient();
    try
    {
        return svc.GetInvalidOrdersCount();
    }
    catch (Exception)
    {
        svc.Abort();
    throw;
    }
    finally
    {
        svc.Close();
    }
}
4

3 に答える 3

1

msdnでは、「適切な」呼び出し方法の例が示されています。

CalculatorClient wcfClient = new CalculatorClient();
try
{
    Console.WriteLine(wcfClient.Add(4, 6));
    wcfClient.Close();
}
catch (TimeoutException timeout)
{
    // Handle the timeout exception.
    wcfClient.Abort();
}
catch (CommunicationException commException)
{
    // Handle the communication exception.
    wcfClient.Abort();
}

クライアントを実装するとき、私は通常このパターンに従います。usingを除いて、あなたはおそらくクライアントのためにを処分したいと思うでしょう:

using (CalculatorClient wcfClient = new CalculatorClient())
{
    try
    {
        return wcfClient.Add(4, 6);
    }
    catch (TimeoutException timeout)
    {
        // Handle the timeout exception.
        wcfClient.Abort();
    }
    catch (CommunicationException commException)
    {
        // Handle the communication exception.
        wcfClient.Abort();
    }
}
于 2013-03-07T13:45:57.167 に答える
1

以下のようなものを使用して、WcfUsingWrapperすべてのプロキシ インスタンスをラップします。

    void Foo(){

        var client = new WcfClientType();
        var result = ExecuteClient(client, x => x.WcfMethod());

      }

    public static ReturnType ExecuteClient<ReturnType>(ClientType client, Func<ClientType, ReturnType> webServiceMethodReference)
where ClientType : ICommunicationObject
    {
        bool success = false;
        try
        {
            ReturnType result = webServiceMethodReference(client);
            client.Close();
            success = true;
            return result;
        }
        finally
        {
            if (!success)
            {
                client.Abort();
            }
        }
    }
于 2013-03-08T13:39:56.363 に答える
0

やりたいことの 1 つは、接続の「状態」を確認することです。チャネルがフォルト状態にある場合は、閉じる前に Abort() メソッドを呼び出す必要があります。そうしないと、チャネルはしばらくの間フォルト状態のままになります。チャネルに障害が発生していない場合は、Close() を呼び出すだけで問題なく動作します。次に、null に設定します。

このようなもの:

 if (requestChannel != null) {
    if (requestChannel.State == System.ServiceModel.CommunicationState.Opened) {
        requestChannel.Close();
        requestChannel = null;
    }

    if (requestChannel.State == System.ServiceModel.CommunicationState.Faulted) {
        requestChannel.Abort();
        requestChannel.Close();
        requestChannel = null;
    }
 }
于 2013-03-08T13:28:12.667 に答える