首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

工作流程式設計循序漸進 (4-5):InvokeWorkflowActivity 本地服務與宿主通訊完整實現

     編輯:關於C語言

InvokeWorkflowActivity 非同步呼叫子工作流:本地服務定義與宿主協調完整代碼

一、本地服務介面定義


[ExternalDataExchange]
internal interface ILocalService {
    event EventHandler InvokedWorkflowComplete;
    void WorkComplete(Guid HostWFGuid);
}

二、本地服務實現類別


internal class LocalService : ILocalService {
    public event EventHandler InvokedWorkflowComplete;
    
    public void WorkComplete(Guid HostWFGuid) {
        if (InvokedWorkflowComplete != null) {
            InvokedWorkflowComplete(null, new ExternalDataEventArgs(HostWFGuid));
        }
    }
}

三、宿主程式完整代碼 (Program.cs)


using System;
using System.Workflow.Runtime;
using System.Workflow.Runtime.Hosting;
using System.Workflow.Activities; // ExternalDataExchangeService
using System.Threading;

namespace InvokeWorkflowActivityDemo {
    class Program {
        static Guid HostWFGuid;
        static LocalService ls;
        
        static void Main(string[] args) {
            using (WorkflowRuntime workflowRuntime = new WorkflowRuntime()) {
                // 必須套路:載入本地資料交換服務
                ExternalDataExchangeService dataService = new ExternalDataExchangeService();
                workflowRuntime.AddService(dataService);
                
                // 註冊自訂本地服務
                ls = new LocalService();
                dataService.AddService(ls);
                
                AutoResetEvent waitHandle = new AutoResetEvent(false);
                workflowRuntime.WorkflowCompleted += delegate(object sender, WorkflowCompletedEventArgs e) {
                    if (e.WorkflowInstance.InstanceId != HostWFGuid) {
                        // 子工作流完成 → 通知父工作流
                        ls.WorkComplete(HostWFGuid);
                    } else {
                        // 父工作流完成 → 釋放等待
                        waitHandle.Set();
                    }
                };
                workflowRuntime.WorkflowTerminated += delegate(object sender, WorkflowTerminatedEventArgs e) {
                    Console.WriteLine(e.Exception.Message);
                    waitHandle.Set();
                };
                
                WorkflowInstance instance = workflowRuntime.CreateWorkflow(typeof(Workflow1));
                HostWFGuid = instance.InstanceId;
                instance.Start();
                waitHandle.WaitOne();
                Console.ReadLine();
            }
        }
    }
}

關鍵點:啟動工作流前必須加載 ExternalDataExchangeService 並註冊自訂服務 (MSDN 規定)。

四、執行結果

執行結果截圖
圖 1:父子工作流協調執行結果
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved