我正在使用一个 WCF 服务,并且到目前为止一直表现良好。
但是,在我们的流量很大的生产系统上,我注意到,在内存逐渐一致上升和下降之后(之间的时间逐渐拉长,增量逐渐增加),内存消耗呈上升趋势。
我想知道这是否可能是由于我使用 DAL Web 服务的方式造成的:
例如:
public static int GetUserTypeFromProfileID(int profileID)
{
try
{
memberServiceClient = new MemberServiceClient(); // connect to the data service
return memberServiceClient.GetUserTypeFromProfileID(profileID); // get the profileID associated with the sessionID
}
catch (Exception ex)
{
ErrorLogging.Instance.Fatal(ex);
return 0;
}
}
如果我使用 using
语句将其更改为以下内容:
public static int GetProfileIDFromSessionID(string sessionID)
{
try
{
using (memberServiceClient = new MemberServiceClient()) // connect to the data service
{
return memberServiceClient.GetProfileIDFromSessionID(sessionID); // get the profileID associated with the sessionID
}
}
catch (Exception ex)
{
ErrorLogging.Instance.Fatal(ex);
return 0;
}
}
在 using
部分中执行返回是否合适?
最佳答案
我相信 using 语句对于 WCF 没有任何特定的内容。它会在返回值之前处理您的 MemberServiceClient。
但是 WCF 服务客户端上的 Dispose() 方法调用 Close()里面的方法,可能会抛出异常。所以最好直接调用 Close() 方法。您还应该调用Abort()发生异常时的方法。这是推荐的实现。
var result;
try
{
memberServiceClient = new MemberServiceClient();
result = memberServiceClient.GetUserTypeFromProfileID(profileID);
memberServiceClient.Close();
}
catch (FaultException e)
{
//handle exception
memberServiceClient.Abort();
}
catch (CommunicationException e)
{
//handle exception
memberServiceClient.Abort();
}
catch (TimeoutException e)
{
//handle exception
memberServiceClient.Abort();
}
注意:我编写了一个简单的基类来处理这些细节。已开启 NuGet .
更新:
以下是按要求使用 WcfClientBase 的示例:
public class MemberServiceManager : ServiceClientBase<MemberServiceClient>
{
public int GetUserTypeFromProfileID(int profileID)
{
//makes a call to GetUserTypeFromProfileID operation, closes the channel and handles the exceptions
//you may want to implement another base class for overriding exception handling methods
//return value will be default of return type if any exceptions occur
return PerformServiceOperation(item => item.GetUserTypeFromProfileID(profileID));
}
//or you can manually check if any exceptions occured with this overload
public bool TryGetUserTypeFromProfileID(int profileID, out int userType)
{
return TryPerformServiceOperation(item => item.GetUserTypeFromProfileID(profileID), out userType);
}
//these exception handling methods should be overriden in another common subclass
//they re-throw exceptions by default
protected override void HandleCommunicationException(CommunicationException exception)
{
Console.WriteLine(exception.Message);
}
protected override void HandleFaultException(FaultException exception)
{
Console.WriteLine(exception.Message);
}
protected override void HandleTimeoutException(TimeoutException exception)
{
Console.WriteLine(exception.Message);
}
}
您还可以查看 GitHub 上的源代码
关于c# - 使用 WCF 服务时,从 using 语句中返回是否是一种好的形式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11215530/