using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Workflow.Runtime;
using System.Threading;

namespace WorkflowHost
{
    class Program
    {
        private static AutoResetEvent waitHandle = new AutoResetEvent(false);
        static void Main(string[] args)
        {
            WorkflowRuntime workflowRuntime = WorkflowFactory.GetWorkflowRuntime();
            workflowRuntime.WorkflowIdled += new EventHandler<WorkflowEventArgs>(workflowRuntime_WorkflowIdled);
            workflowRuntime.WorkflowCompleted += new EventHandler<WorkflowCompletedEventArgs>(workflowRuntime_WorkflowCompleted);
            workflowRuntime.WorkflowTerminated += new EventHandler<WorkflowTerminatedEventArgs>(workflowRuntime_WorkflowTerminated);
            Int32 delay = 0;
            string val = args.Length > 0 ? args[0] : "10";
            if (!Int32.TryParse(val, out delay))
            {
                Console.WriteLine("你必须输入一个整形值!");
                return;
            }

            Dictionary<string, object> parms = new Dictionary<string, object>();
            parms.Add("Delay", delay);
            Console.WriteLine("等待workflow完成({0}秒...)。", val);
            WorkflowInstance instance = workflowRuntime.CreateWorkflow(typeof(LongRunningWorkflow.Workflow1), parms);
            instance.Start();
            Console.WriteLine("workflow处在：{0}状态。", instance.GetWorkflowDefinition().ExecutionStatus.ToString());
            instance.Terminate("用户取消");
            waitHandle.WaitOne();
            Console.WriteLine("结束。");
            Console.ReadLine();
        }
        
        static void workflowRuntime_WorkflowIdled(object sender, WorkflowEventArgs e)
        {
            Console.WriteLine("workflow实例空闲中。");
        }

        static void workflowRuntime_WorkflowCompleted(object sender, WorkflowCompletedEventArgs e)
        {
            Console.WriteLine("workflow实例已完成。");
            waitHandle.Set();
        }
        static void workflowRuntime_WorkflowTerminated(object sender, WorkflowTerminatedEventArgs e)
        {
            Console.WriteLine("workflow实例已终止,原因：'{0}'。",e.Exception.Message);
            waitHandle.Set();
        }
    }
}
