c# - WF4 中的状态机

标签 c# workflow-foundation-4

首先是免责声明 - 我是 WF 新手,而且我只玩了 WF4 3 天 - 所以对于我可能遇到的任何善意或蹩脚的问题深表歉意......

我正在尝试在我的项目中实现 WF4 状态机。以下是一些背景信息:

  1. 我有 WinForm UI 作为主应用程序,可以为网络堆栈生成不同的命令
  2. 我将接口(interface)层作为从网络堆栈接收事件的 DLL
  3. 状态机应在与接口(interface)层并行的中间层中的某个位置实现软件电话状态机。电话状态根据网络事件和用户操作而变化。有些用户操作只会导致网络命令,有些可能会直接影响状态机。
  4. 我的接口(interface)层实现了一个对象 Phone,因此我将该对象作为状态机的主机。我将主界面对象 WinSipItf 传递给电话对象,并执行以下操作(WinSipItf 对象位于另一个命名空间 WinSipNetLib 中):

代码:

public void Initialize(WinSipNetLib.WinSipItf winSipItf, string hostname, string user, string password)
{
    try
    {
        WinSipItf = winSipItf;
        var Itf = WinSipItf;
        var input = new Dictionary<string, object>
                    {
                        {"winSipItf", Itf}
                    };
        this.WorkFlowHostApp = new WorkflowApplication(new Activity1(), input)
        {
            Idle = this.OnWorkflowIdle,
            Completed = this.OnWorkflowCompleted
        };

        // Setup the Tracking to output in the debug window
        WorkFlowHostApp.Extensions.Add(new Tracker());

        this.WorkFlowHostApp.Extensions.Add(this);

        this.workflowBusy.Reset();

        Console.WriteLine("Starting Workflow");
        this.WorkFlowHostApp.Run();
    }
    catch (Exception ex)
    {
        Console.Write(ex);
    }
}

电话初始状态为Initial,并且具有目标状态PhoneIdle 的自动/空触发器。 OnEntrace 到初始状态我需要使用网络堆栈执行几个电话注册 - 注册回调(同步操作)并使用网络堆栈管理器注册(异步)。所有这些功能都位于较低级别的非托管代码中,我可以通过接口(interface)层中构造的 API 访问这些代码。成功注册后,我会在接口(interface)层收到回调并触发事件。因此我的注册事件如下所示:

public sealed class Register : NativeActivity<Int32>
{
    // Define an activity input argument of type string
    [RequiredArgument]
    public InArgument<WinSipNetLib.WinSipItf> winSipItf { get; set; }

    #region Constants and Fields

    private readonly Variable<NoPersistHandle> _noPersistHandle = new Variable<NoPersistHandle>();
    internal const string BookmarkName = "WaitingForAccountStatusEvent";

    /// <summary>
    /// The transition callback.
    /// </summary>
    private BookmarkCallback registrationCallback;

    #endregion

    #region Properties

    ///// <summary>
    /////   Gets or sets PhoneTransition.
    ///// </summary>
    //public PhoneTransition PhoneTransition { get; set; }

    /// <summary>
    ///   Gets a value indicating whether CanInduceIdle.
    /// </summary>
    protected override bool CanInduceIdle
    {
        get
        {
            return true;
        }
    }

    /// <summary>
    /// Gets TransitionCallback.
    /// </summary>
    private BookmarkCallback RegistrationCallback
    {
        get
        {
            return this.registrationCallback ?? (this.registrationCallback = new BookmarkCallback(this.OnRegistrationCallback));
        }
    }

    #endregion

    #region Methods

    /// <summary>
    /// The cache metadata.
    /// </summary>
    /// <param name="metadata">
    /// The metadata.
    /// </param>
    protected override void CacheMetadata(NativeActivityMetadata metadata)
    {
        metadata.RequireExtension(typeof(Tracker));
        metadata.RequireExtension(typeof(Phone));
        metadata.RequireExtension(typeof(WaitForRegistrationExt));
        // !!! and one more for GUI

        // Provide a Func<T> to create the extension if it does not already exist
        metadata.AddDefaultExtensionProvider(() => new WaitForRegistrationExt());

        metadata.AddArgument(new RuntimeArgument("winSipItf", typeof(WinSipNetLib.WinSipItf), ArgumentDirection.In, true));
        metadata.AddArgument(new RuntimeArgument("Result", typeof(int), ArgumentDirection.Out, false));

        metadata.AddImplementationVariable(_noPersistHandle);
    }

    protected override void Execute(NativeActivityContext context)
    {
        // Enter a no persist zone to pin this activity to memory since we are setting up a delegate to receive a callback
        var handle = _noPersistHandle.Get(context);
        handle.Enter(context);

        // Get Phone extension needed to call the functions in WinSipItf
        Phone phone = (Phone)context.GetExtension<Phone>();

        // Get (which may create) the extension
        WaitForRegistrationExt regExt = context.GetExtension<WaitForRegistrationExt>();

        // Add the callback
        regExt.AddRegistrationCallback(winSipItf.Get(context));

        bool bRet = phone.WinSipItf.RegisterDBusCallback("WinSipPhone");

        // Obtain the runtime value of the Text input argument
        if (bRet == false)
        {
            this.Result.Set(context, bRet.ToString());
            return;
        }

        string hostname = "demo2.demo.com";
        string username = "406";
        string password = "123123"; 
        string id = username + "@" + hostname;
        String regUri = hostname;
        if (phone.WinSipItf.DoSipRegister(id, regUri, username, password) == 0)
        {
            this.Result.Set(context, bRet.ToString());
            return;
        }

        // Set a bookmark - the extension will resume when the Gizmo is fired
        context.CreateBookmark(BookmarkName, RegistrationCallback);

        //context.CreateBookmark(this.PhoneTransition.ToString(), this.RegistrationCallback);

        //// Obtain the runtime value of the Text input argument
        //string text = context.GetValue(this.Text);

        //Result.Set(context, string.Format("The text is {0}", text));
    }

    /// <summary>
    /// The on transition callback.
    /// </summary>
    /// <param name="context">
    /// The context.
    /// </param>
    /// <param name="bookmark">
    /// The bookmark.
    /// </param>
    /// <param name="value">
    /// The value.
    /// </param>
    /// <exception cref="InvalidOperationException">
    /// </exception>
    private void OnRegistrationCallback(NativeActivityContext context, Bookmark bookmark, object value)
    {
        if (value is WinSipItf.MSGDATA)
        {

        }
        ////if (value is StateTransitionResult)
        //{
        //    this.Result.Set(context, value as StateTransitionResult);
        //}
        //else if (value != null)
        //{
        //    // Resumed with something else
        //    throw new InvalidOperationException(
        //        "You must resume PhoneTransition bookmarks with a result of type StateTransitionResult");
        //}

        // Exit the no persist zone 
        var handle = _noPersistHandle.Get(context);
        handle.Exit(context);
    }

    #endregion
}

正如您从我进行的调用的代码中看到的那样:phone.WinSipItf.DoSipRegister 有效吗?我认为所有状态机都在与构造 WinSipItf 对象的线程不同的线程上执行...... 多余地说,我对此一无所获......我什至无法中断执行或缓存元数据。不知道此时该怎么办。 值得一提的是,我的 xaml 图已经构建完成,但我试图通过构建此自定义事件来仅实现初始状态及其到空闲状态的转换...

也许我应该从一个简单的问题开始:当我将注册事件放在初始状态条目上时,我收到“未提供所需事件参数‘winSipItf’的值”警告。我检查了所有代码,但不明白为什么。我错过了什么?

最佳答案

首先,由于您是工作流程新手,您可能想要执行 Introduction to State Machine Hands On Lab .

第二 - 我有一个示例应用程序,演示如何支持回调(是的,工作流程在不同的线程上执行)Windows Workflow Foundation (WF4) - Activity Callbacks and Event Handlers

关于c# - WF4 中的状态机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7590444/

相关文章:

C# 将对象 [ ] 转换为字节 [ ],但如何将字节对象保留为字节?

Windows Workflow Foundation 4 (WF4) 延迟

用于将数据写入 OpenTSDB 的 C# 代码

c# - 如何在暂停/持久化后正确加载工作流?

.net - Workflow 4.0 缓存元数据与缓存完整事件对象

wcf - WF4/WCF 中的 RESTful 工作流服务端点

c# - SqlWorkflowInstanceStore WaitForEvents 返回 HasRunnableWorkflowEvent 但 LoadRunnableInstance 失败

c# - .net 核心类库中的不同字符编码

c# - 隔离类仅由特定类 : best practices 实例化

c# - 如何通过 ServiceBehavior 配置启用 WCF 帮助页面?