gpt4 book ai didi

c# - WCF 通话 - 最佳实践

转载 作者:行者123 更新时间:2023-12-02 12:27:31 28 4
gpt4 key购买 nike

这个问题的两个小部分希望能为我消除一些歧义。

首先,调用WCF服务哪个更好?

using (var myService = new ServiceClient("httpBinding")){
try{
var customerDetails = GetCustomerDetails();
var results = myService.GetCustomerPurchases(customerDetails);
}catch(Exception e){
......
}
}

var myService = new ServiceClient("httpBinding");
try{
var customerDetails = GetCustomerDetails();
var results = myService.GetCustomerPurchases(customerDetails);
}catch(Exception e){
.......
}

我想知道的是,我是否应该始终将服务调用包装在 using block 中?如果服务抛出异常,IDisposable.Dispose() 会被调用吗?

最佳答案

看看this问题。

您还可以创建几个类,例如

public class ClientService<TProxy>
{
private static ChannelFactory<TProxy> channelFactory = new ChannelFactory<TProxy>("*");

public static void SendData(Action<TProxy> codeBlock)
{
var proxy = (IClientChannel) channelFactory.CreateChannel();
bool success = false;

try
{
codeBlock((TProxy)proxy);
proxy.Close();
success = true;
}
finally
{
if (!success)
{
proxy.Abort();
}
}
}

public static TResult GetData<TResult>(Func<TProxy, TResult> codeBlock)
{
var proxy = (IClientChannel) channelFactory.CreateChannel();
bool success = false;

TResult result;
try
{
result = codeBlock((TProxy)proxy);
proxy.Close();
success = true;
}
finally
{
if (!success)
{
proxy.Abort();
}
}

return result;
}
}

public class SomeAnotherService<TProxy>
{
public static bool SendData(Action<TProxy> codeBlock)
{
try
{
ClientService<TProxy>.SendData(codeBlock);
return true;
}
catch(Exception ex)
{
//...
}
return false;
}

public static TResult GetData<TResult>(Func<TProxy, TResult> codeBlock)
{
TResult result = default(TResult);
try
{
result = ClientService<TProxy>.GetData(codeBlock);
}
catch (Exception ex)
{
//...
}

return result;
}
}

有时候很方便。这是调用某些服务方法的示例。

var someObj = SomeAnotherService<IMyService>.GetData(x => x.SomeMethod());

关于c# - WCF 通话 - 最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11046821/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com