ฉันมีคลาสที่ใช้ IDisposable ตาม รูปแบบนี้ เพราะ มีการอ้างอิงถึง HttpClient มีลักษณะดังนี้:
public class CustomServiceClient : IDisposable
{
HttpClient client;
// ...
public ServiceCreatedEntity GetEntity()
{
// ...
}
~CustomServiceClient()
{
this.Dispose(false);
}
private bool disposed = false;
void IDisposable.Dispose()
{
if(!disposed)
{
this.Dispose(true);
GC.SuppressFinalize(this);
disposed = true;
}
}
public void Dispose(bool disposing)
{
if(disposing)
{
// dispose managed resources
client.Dispose();
}
// dispose unmanaged resources - this class has none
}
}
public class ServiceCreatedEntity
{
CustomServiceClient client;
public ServiceCreatedEntity(CustomServiceClient client)
{
this.client = client;
}
// some functions that use client
}
ฉันสงสัยว่า ServiceCreatedEntity
ควรใช้ IDisposable และกำจัด CustomServiceClient หรือไม่ โดยทั่วไป ฉันคาดว่า CustomServiceClient
จะมีอายุการใช้งานยาวนานกว่า ServiceCreatedEntity
และฉันกังวลว่าลูกค้าจะกำจัด ServiceCreatedEntity
และสับสนว่าทำไม CustomServiceClient
ของพวกเขาจึงถูกกำจัดเช่นกัน คำแนะนำใด ๆ ที่จะได้รับการชื่นชมอย่างมาก!
ServiceCreatedEntity
หากพวกเขาจัดการกับไคลเอนต์เสร็จแล้วเช่นกัน แต่ความแตกต่างที่นี่คือ StreamReaders/Writers/etc ถูกสร้างขึ้นอย่างชัดเจนด้วยโอเปอเรเตอร์ใหม่ (RAII และทั้งหมดนั้น) ดังนั้นผู้สร้างจึงถูกคาดหวังให้เป็นเจ้าของอ็อบเจ็กต์ ในขณะที่ServiceCreatedEntity
ถูกสร้างอินสแตนซ์และส่งคืนโดยCustomServiceClient
ซึ่งจะบ่งชี้ว่าบางทีผู้สร้างไม่ได้เป็นเจ้าของมัน - person Andrew Gaspar   schedule 01.07.2014