对于从 System.EnterpriseServices.ServicedComponent 类派生的类,可以使用 COM+ 对象池来避免从头实例化对象的开销。COM+ 对象池不是从头开始实例化对象,而是在激活时从池中提取对象。有关详细信息,请参阅对象池。
创建池对象并设置其大小和超时限制
- 定义一个从 System.EnterpriseServices.ServicedComponent 类派生的类,并将 ObjectPoolingAttribute 属性应用于该类。例如,以下代码定义一个名为 - TestObjectPooling的类并为该类设置 MinPoolSize、MaxPoolSize 和 CreationTimeout 属性。- <ObjectPooling(MinPoolSize := 2, MaxPoolSize := 5, _ CreationTimeout := 20000)> _ Public Class TestObjectPooling Inherits ServicedComponent End Class- [ObjectPooling(Enabled=true, MinPoolSize=2, MaxPoolSize=5, CreationTimeout=20000)] public class TestObjectPooling : ServicedComponent { }
- 重写 System.EnterpriseServices.ServicedComponent 类的 Activate、Deactivate 和 CanBePooled 方法。 
- 在客户端应用程序中测试池对象: - 创建池对象类的一个实例并对池对象调用这些方法。例如,以下代码创建 - TestObjectPooling类的一个实例并调用- Perform方法。- Public Class App Overloads Public Shared Sub Main(args() As String) Dim order As New TestObjectPooling() order.Perform()- public class App { public static int Main(string[] args) { TestObjectPooling order = new TestObjectPooling(); order.Perform();
- 调用 DisposeObject 方法,将对象返回到池中。 - ServicedComponent.DisposeObject (order)- ServicedComponent.DisposeObject (order);
 
示例
<ObjectPooling(MinPoolSize := 2, MaxPoolSize := 5, _
CreationTimeout := 20000)> _
Public Class TestObjectPooling 
Inherits ServicedComponent
      Public Sub Perform ()
            ' Method contents go here.
      End Sub 
      Protected Overrides Sub Activate()
            ' Called when removed from the pool.
      End Sub 
      Protected Overrides Sub Deactivate()
            ' Called before deactivating or placing back in pool.
      End Sub 
      Protected Overrides Function CanBePooled() As Boolean
            ' Called after Deactivate. Indicate your vote here.
            Return True
      End Function 
End Class 
[ObjectPooling(Enabled=true, MinPoolSize=2, MaxPoolSize=5, CreationTimeout=20000)]
public class TestObjectPooling : ServicedComponent
{
      public void Perform ()
      {
         // Method contents go here.
      }
      protected override void Activate()
      {
         // Called when removed from the pool.
      }
      protected override void Deactivate()
      {
         // Called before deactivating or placing back in pool.
      }
      protected override bool CanBePooled()
      {
         // Called after Deactivate. Indicate your vote here.
         return true;
      }
}
 
请参见
参考
ObjectPoolingAttribute
System.EnterpriseServices Namespace
概念
.gif)
版权所有 (C) 2007 Microsoft Corporation。保留所有权利。