每次触发自定义事件时执行流程

时间:2011-08-18 21:49:15

标签: workflow-foundation-4 bookmarks native-activity

Workflow

每次观看文件触发事件时,我都需要执行显示创建的文件名

WatchFilesActivity:NativeActivity

    protected override void Execute(NativeActivityContext context)
    {
        var fileSystemWatcher = new FileSystemWatcher(context.GetValue(Path));
        fileSystemWatcher.IncludeSubdirectories = context.GetValue(IncludeSubdirectories);
        fileSystemWatcher.Filter = context.GetValue(Filter);

        var bookmark = context.CreateBookmark(ResumeFileCreatedBookmark);
        context.GetExtension<FileSystemWatcherExtension>().Start(fileSystemWatcher, bookmark);
    }

扩展

    public class FileSystemWatcherExtension : IWorkflowInstanceExtension
    {
        WorkflowInstanceProxy instance;
        Bookmark bookmark;

        public void SetInstance(WorkflowInstanceProxy instance)
        {
            this.instance = instance;
        }

        IEnumerable<object> IWorkflowInstanceExtension.GetAdditionalExtensions()
        {
            yield break;
        }

        public void Start(FileSystemWatcher fileSystemWatcher, Bookmark bookmark)
        {
            this.bookmark = bookmark;
            fileSystemWatcher.Created += new FileSystemEventHandler(FileCreated);
            fileSystemWatcher.EnableRaisingEvents = true;
        }

        void FileCreated(object sender, FileSystemEventArgs e)//When the file arrives
        {
            instance.BeginResumeBookmark(bookmark, e.FullPath, CompleteResume, null);
        }

        void CompleteResume(IAsyncResult ar)
        {
            var result = instance.EndResumeBookmark(ar);
        }
    }

这很有效,但只有一次,然后主机关闭。

我不能放一个WhileActivity,因为我需要处理连续非常快的文件创建和传入文件的处理时间(在这种情况下显示创建的文件名)大于文件创建速率

谢谢!

1 个答案:

答案 0 :(得分:2)

对于初学者,我会将显示创建的文件名活动设为监视文件活动的子活动,以便它可以控制它的执行。接下来,我将添加书签恢复回调,以便监视文件活动可以对回调中的显示创建的文件名活动作出反应并安排。

您可能希望使用BookmarkOptions.MultipleResume创建书签,这样您就可以根据需要处理任意数量的文件事件,并且只在您想要的时候继续。

public class WatchFilesActivity : NativeActivity
{
    public Activity Child {get; set;}

    protected override void Execute(NativeActivityContext context)
    {
        var fileSystemWatcher = new FileSystemWatcher(context.GetValue(Path));
        fileSystemWatcher.IncludeSubdirectories = context.GetValue(IncludeSubdirectories);
        fileSystemWatcher.Filter = context.GetValue(Filter);

        var bookmark = context.CreateBookmark(ResumeFileCreatedBookmark, OnFileCreated, BookmarkOptions.MultipleResume);
        context.GetExtension<FileSystemWatcherExtension>().Start(fileSystemWatcher, bookmark);
    }

    protected void OnFileCreated(NativeActivityContext context, Bookmark bookmark, object value)
    {
        var fileName = (string)value
        context.ScheduleActivity(Child);
    }
}

注意:在记事本中键入的代码可能存在拼写错误。

如果您需要将文件名传递给子活动,您可以使用ActivityAction来执行此操作。有关使用ActivityFunc的示例,请参阅here,它与ActivityAction类似,但它也有返回值。