3

WCF Web サービス メソッドを安全に呼び出す方法を知りたいです。これらの方法は両方とも許容可能/同等ですか? より良い方法はありますか?

最初の方法:

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

2 番目の方法:

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

クライアントが適切に閉じられ、処分されていることを確認したい。

ありがとう

4

3 に答える 3

4

例外をスローする可能性があるため、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
    }
}

これらの 2 つの場合:

var client = new WebServicesClient();
return client.SafeExecute(c => c.GetThing());
于 2010-08-17T10:44:55.797 に答える
1

2 番目の方法は、例外が発生する可能性があるという事実に対処しているため、わずかに優れています。特定の例外をトラップして、少なくともログに記録した方がよいでしょう。

ただし、このコードは戻るまでブロックされGetThingます。これが迅速な操作であれば問題にはならないかもしれませんが、それ以外の場合は、非同期メソッドを作成してデータを取得することをお勧めします。これにより、完了を示すイベントが発生し、そのイベントをサブスクライブして UI (または実行する必要があるもの) を更新します。

于 2010-08-17T10:45:12.917 に答える
0

そうではありません:

于 2010-08-17T10:45:10.680 に答える