我需要创建一个维护WCF会话的服务.在构造函数中,我从数据库中读取数据,当会话结束时,我必须将其保存回来.
如果我理解正确,当我在客户端上调用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;
}
}
Run Code Online (Sandbox Code Playgroud)
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" > …Run Code Online (Sandbox Code Playgroud) 我正在尝试创建一个简单的类,它在不再使用时将自身序列化为磁盘.我现在的代码(见下文).我现在的代码似乎有用,但我对自己的知识并不完全自信,所以我想知道是否有其他人看到这个代码有任何重大问题.
void IDisposable.Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~MyClass()
{
Dispose(false);
}
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
MemoryStream ms = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms, this);
byte[] output = Dostuff(ms);
File.WriteAllBytes(DBPATH, output);
}
this.disposed = true;
}
Run Code Online (Sandbox Code Playgroud)