处理异步事件和运行大量后处理代码的最佳实践

问题描述 投票:0回答:1

异步事件处理程序

我有这个类来异步运行可执行文件:


namespace Feather
{
    internal class Helper
    {
        private static Process cmd;

        public static void RunLogic(string args)
        {
            cmd = new Process();

            cmd.StartInfo.FileName = "Cotton.exe";
            cmd.StartInfo.Arguments = args;
            cmd.EnableRaisingEvents = true;
            cmd.Exited += new EventHandler(cmd_Exited);
        }

        private static void cmd_Exited(object sender, EventArgs e)
        {
            // Process finished.
            cmd.Dispose();

            // An output file is generated by the executable.
            // The output file needs post-processing.
            // Post-processing is a huge code base.
            // TODO: Best practice to run huge post-processing code here?
        }
    }
}

触发

我触发 exe 从另一个类中运行,如下所示:


namespace Feather
{
    public class FeatherHollow : Command
    {

        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            string args = "";

            // Trigger async run of the executable.
            Helper.RunLogic(args);

            // TODO: How to run the huge post-processing code when the output file
            // is generated by the executable.

            return Result.Success;
        }
    }
}

问题

异步进程完成时运行大量后处理代码的最佳实践和最简单方法是什么?

delegate
方法

这是最好的方法吗?


namespace Feather
{
    internal class Helper
    {
        public delegate void PostProcess(object sender, EventArgs e);

        public static void RunLogic(string args, PostProcess pp)
        {
                // ...
                cmd.Exited += new EventHandler(cmd_Exited);
                cmd.Exited += new EventHandler(pp);
                // ...
        }
    }
}

和调用者类别:


namespace Feather
{
    public class FeatherHollow : Command
    {
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            // ...
            Helper.RunLogic(args, PostProcess);
            // ...
        }

        private static void PostProcess(object sender, EventArgs e)
        {
            // Huge post-processing code is here.
        }
    }
}
c# .net asynchronous event-handling .net-4.0
1个回答
1
投票

我建议使用任务和异步等待:

public static Task RunLogic(string args, CancellationToken cancel = default)
{
    cmd = new Process();
    // ...

   return cmd.WaitForExitAsync(cancel);
}

这允许您在调用方法时使用await,并且这往往使代码比使用委托/回调更易于阅读。

await RunLogic(...);
// do post process stuff

如果你想从

RunLogic
返回一个值:

public static async Task<string> RunLogic(string args, CancellationToken cancel = default)
{
    cmd = new Process();
    // ...

   await cmd.WaitForExitAsync(cancel);
   
   return myResultValue;
}

如果您使用的是旧版本的 .Net,您可以使用

TaskCompletionSource
复制相同的功能。

© www.soinside.com 2019 - 2024. All rights reserved.