看了DUDU的两篇文章:

文1:http://www.cnblogs.com/dudu/archive/2011/11/02/wcf_client_no_using_call.html

文2:http://www.cnblogs.com/dudu/archive/2011/12/31/wcfclient.html

基于这篇文章所描述的需要两种方式支持有无返回值的函数,在REF和OUT支持也会受限制

今天有一种构想就是:

    public class ServiceInvoke<T>
{
public static T Invoke()
{
var chanFactory = new ChannelFactory<T>("*");
return chanFactory.CreateChannel();
}
}

将函数名在外面调用。

有一个问题就是如何能够在调用完函数后自动的释放WCF连接。

整理得到的WCF调用类

internal class ServiceInvoker<T>
{
private T channel;

public T Invoke()
{
var chanFactory = new ChannelFactory<T>("*");
UserNamePasswordClientCredential credentials = chanFactory.Credentials.UserName;
credentials.UserName = "Name";
credentials.Password = "Pass";
channel = chanFactory.CreateChannel();
return channel;
}
~ServiceInvoker()
{//通过析构函数来回收链接,但不能实时回收
if (channel != null)
{
ICommunicationObject ICO = channel as ICommunicationObject;
if (ICO.State == CommunicationState.Faulted)
ICO.Abort();
if (ICO.State != CommunicationState.Closed || ICO.State != CommunicationState.Closing)
ICO.Close();
}
}
}
internal static class Service<T>
{
public static T Invoke()
{
return new ServiceInvoker<T>().Invoke();
}
}

那么我们在调用的时候,就可以直接使用Service<T>的方式了。

如:

var infoList = Service<ServiceReference1.IService>.Invoke().GetList(1);


一个类就可以实现可有无返回值以及引用值类型的函数了。

 

PS:今天发现,即时关闭通信链接,也会耗1分30秒左右才会进行资源释放。采用析构函数的话,也是同样的结果。

相关文章:

  • 2022-12-23
  • 2021-07-11
  • 2022-12-23
  • 2022-12-23
  • 2021-10-03
  • 2021-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-07-13
  • 2021-11-11
  • 2022-12-23
相关资源
相似解决方案