在WCF服务中调用析构函数时

本文关键字:析构函数 调用 WCF 服务 | 更新日期: 2023-09-27 18:07:33

我需要创建一个服务,它将维护一个WCF会话。在构造函数中,我从DB中读取数据,当会话结束时,我必须将其保存回来。

如果我理解正确,当我在客户端上调用Close()时会话结束(我的客户端ServiceClient是用SvcUtil.exe创建的)。

当我测试它时,我看到它有时在大约之后被调用。10分钟,有时20分钟后,有时根本没有。

那么什么时候调用析构函数呢?

服务
   [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
   public class Service:IService
   {
     private User m_User = null;
     public  Service()
     {
       m_User = User.LoadFromDB();
     }
     ~Service()
     {
       m_User.SaveToDB();
     }
     public void SetName(string p_Name)
     {
       m_User.Name = p_Name;
     }
    }

web . config

<?xml version="1.0"?>
<configuration>
  <system.web>
    <sessionState timeout="2" />
  </system.web>
  <system.serviceModel>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
      <services>
        <service name="Karatasi.Services.B2C"  behaviorConfiguration="ServiceBehavior">
          <host>
            <baseAddresses>
              <add baseAddress="http://localhost:19401/B2C.svc"/>
            </baseAddresses>
          </host>
        <endpoint
           address=""
           binding="wsHttpBinding"
           bindingConfiguration="test"
           contract="Karatasi.Services.IB2C"
         />
        <endpoint
           address="mex"
           binding="mexHttpBinding"
           contract="IMetadataExchange"
         />
       </service>
     </services>
   <bindings>
     <wsHttpBinding>
       <binding name="test" receiveTimeout="00:01:00" >
         <reliableSession enabled="true" ordered="false" inactivityTimeout="00:01:00"/>
       </binding>
     </wsHttpBinding>
    </bindings>
  <behaviors>
    <serviceBehaviors>
      <behavior name="ServiceBehavior">
        <serviceMetadata httpGetEnabled="true" />
        <serviceDebug includeExceptionDetailInFaults="false" />
      </behavior>
    </serviceBehaviors>
  </behaviors>
</system.serviceModel>
</configuration>
客户

    ServiceClient serviceClient = null;
    try
    {
      serviceClient = new ServiceClient();
      serviceClient.SetName("NewName");
      Console.WriteLine("Name set");
    }
    catch (Exception p_Exc)
    {
      Console.WriteLine(p_Exc.Message);
    }
    finally
    {
      if (serviceClient != null)
      {
        if (serviceClient.State == CommunicationState.Faulted)
        {
          serviceClient.Abort();
        }
        else
        {
          serviceClient.Close();
        }
      }
      Console.ReadKey();
    }

在WCF服务中调用析构函数时

From docs

程序员无法控制何时调用析构函数因为这是由垃圾回收器决定的。垃圾收集器检查不再被使用的对象应用程序。如果它认为一个物体有资格销毁,它调用析构函数(如果有的话)并回收用于存储的内存对象。当程序退出时也会调用析构函数。

你的实现有一个问题。要持久化数据,可以使用析构函数。这是错误的,因为析构函数不能确定地调用,它们在单独的结束队列中处理。这意味着即使你销毁了对象,它的析构函数也可能不会被立即调用。

如何修复
删除析构函数并使用IDisposable模式,将save逻辑放入Dispose中。一旦会话终止,WCF将调用IDisposable。处理

public class Service:IService, IDisposable
{
    public void Dispose()
    {
        //your save logic here
    }
}

编辑
也请看看对这个答案的评论。我实际上同意IDisposable不是数据库提交的合适位置,我以前没有想到过。除了评论中提供的解决方案之外,您还可以使用显式会话划分