code_junkie

What is the most efficient way to handle the lifecycle of an object with COM interop?

Nov 11th, 2011
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. using(WorkflowRuntime workflowRuntime = new WorkflowRuntime())
  6. {
  7. AutoResetEvent waitHandle = new AutoResetEvent(false);
  8. workflowRuntime.WorkflowCompleted += delegate(object sender, WorkflowCompletedEventArgs e)
  9. {
  10. waitHandle.Set();
  11. };
  12. workflowRuntime.WorkflowTerminated += delegate(object sender, WorkflowTerminatedEventArgs e)
  13. {
  14. Console.WriteLine(e.Exception.Message);
  15. waitHandle.Set();
  16. };
  17.  
  18. WorkflowInstance instance = workflowRuntime.CreateWorkflow(typeof(WorkflowConsoleApplication1.Workflow1));
  19. instance.Start();
  20.  
  21. waitHandle.WaitOne();
  22. }
  23. Console.ReadKey();
  24. }
  25. }
  26.  
  27. public sealed partial class Workflow1: SequentialWorkflowActivity
  28. {
  29. public Workflow1()
  30. {
  31. InitializeComponent();
  32. this.codeActivity1.ExecuteCode += new System.EventHandler(this.codeActivity1_ExecuteCode);
  33. }
  34.  
  35. [DebuggerStepThrough()]
  36. private void codeActivity1_ExecuteCode(object sender, EventArgs e)
  37. {
  38. Console.WriteLine("Throw ApplicationException.");
  39. throw new ApplicationException();
  40. }
  41.  
  42. protected override void Dispose(bool disposing)
  43. {
  44. if (disposing)
  45. {
  46. // Here you must free your resources
  47. // by calling your COM helper Dispose() method
  48. Console.WriteLine("Object disposed.");
  49. }
  50. }
  51. }
  52.  
  53. MyComHelper helper = new MyComHelper();
  54. helper.DoStuffWithExcel();
  55. helper.Dispose();
  56. ...
  57.  
  58. MyComHelper helper = new MyComHelper();
  59. try
  60. {
  61. helper.DoStuffWithExcel();
  62. }
  63. finally()
  64. {
  65. helper.Dispose();
  66. }
  67.  
  68. using(MyComHelper helper = new MyComHelper())
  69. {
  70. helper.DoStuffWithExcel();
  71. }
Add Comment
Please, Sign In to add comment