XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEWorkflow

【WinUI】XFE基于windows的工作流

公开
关注 0 Fork 0 Star 0
UTF-8
using XFEWorkflow.Abstractions;
using XFEWorkflow.Infrastructure.Execution;
using XFEWorkflow.Infrastructure.Storage;

namespace XFEWorkflow.Views;

public sealed partial class MainPage
{
    private readonly RunUpdateBuffer runUpdates = new();
    private readonly DispatcherTimer runUpdateTimer = new() { Interval = TimeSpan.FromMilliseconds(150) };
    private bool applyingRunUpdate;
    private string? highlightedRunNode, highlightedRunError;
    private int runUiRefreshCount;

    private void InitializeRunUpdates()
    {
        services.Runs.RunChanged += runChanged = runUpdates.Publish;
        runUpdateTimer.Tick += async (_, _) => await FlushRunUpdateAsync();
        Loaded += (_, _) => { if (!disposed) runUpdateTimer.Start(); };
        Unloaded += (_, _) => runUpdateTimer.Stop();
    }
    private async Task FlushRunUpdateAsync()
    {
        if (disposed || applyingRunUpdate || runUpdates.TakeLatest() is not { } record) return;
        if (record.WorkflowId != ViewModel.SelectedWorkflow?.Id) return;
        applyingRunUpdate = true;
        try
        {
            // Formatting and copying logs stay off the UI thread. Only a bounded,
            // current snapshot is delivered to the controls, even during a log flood.
            var update = await Task.Run(() =>
            {
                var entries = WorkflowLogService.RunEntries(record, 1000);
                string? node; lock (record.Events) node = record.Events.LastOrDefault(x => x.Kind == RunEventKind.NodeStarted)?.NodeId;
                return new { record.WorkflowId, record.Status, record.Error, record.ErrorNodeId, Node = node, Entries = entries, Debug = record.DebugState };
            });
            if (disposed || update.WorkflowId != ViewModel.SelectedWorkflow?.Id) return;
            ViewModel.IsRunning = services.Runs.IsRunning(update.WorkflowId);
            ViewModel.RunLines.ReplaceAll(update.Entries);
            if (highlightedRunNode != update.Node || highlightedRunError != update.ErrorNodeId)
            {
                highlightedRunNode = update.Node; highlightedRunError = update.ErrorNodeId;
                CanvasEditor.HighlightRunNode(update.Node, update.ErrorNodeId);
            }
            ViewModel.Status = update.Status + (update.Error is null ? "" : " · " + update.Error);
            ApplyDebugState(update.Debug);
            runUiRefreshCount++;
        }
        catch (Exception ex) { if (!disposed) ViewModel.Status = "更新运行输出失败:" + ex.Message; }
        finally { applyingRunUpdate = false; }
    }
}