首页 > 解决方案 > 异步运行长同步操作

问题描述

下面我有一个简单的异步示例,它可以按照我的预期使用以下输出:

Starting
Processing Diff
Log Diff Initiated
Diff processed

我需要对此进行调整,以便 GetDiff 是由 LogDiff 异步调用的同步操作。

我的基本场景如下:当用户单击按钮保存项目时,我必须在项目的新版本和旧版本之间生成差异,这是一个昂贵的操作。我不希望用户必须等待这个差异完成,因为他们真正感兴趣的是他们的项目被保存,所以我希望这个同步操作在后台异步执行,这样用户就没有等待它,甚至知道它。

这意味着我什至不需要回调,我只想触发在后台生成此差异的代码。考虑到所有这些,我应该如何调整我的示例来实现这一点?

仅供参考,我在 .net 4.0 上,这就是为什么我在示例中使用了延迟 polyfill 方法。

class Program
{

    static void  Main()
    {
        Console.WriteLine("Starting");
        LogDiff();
        Console.WriteLine("Log Diff Initiated");
        Console.ReadLine();
    }

    public static async Task LogDiff()
    {
        var results = await GetDiff("Processing Diff");
        Console.WriteLine(results);
    }

    public static async Task<string> GetDiff(string str)
    {
        Console.WriteLine(str);
        await Delay(2000);
        return "Diff processed";
    }

    public static Task Delay(double milliseconds)
    {
        var tcs = new TaskCompletionSource<bool>();
        System.Timers.Timer timer = new System.Timers.Timer();
        timer.Elapsed += (obj, args) =>
        {
            tcs.TrySetResult(true);
        };
        timer.Interval = milliseconds;
        timer.AutoReset = false;
        timer.Start();
        return tcs.Task;
    }
}

标签: c#asp.netasynchronous.net-4.0

解决方案


为什么不在LogDiff()分离任务中执行繁重的方法?

    static void  Main()
    {
        Console.WriteLine("Starting");
        //Save project
        Console.WriteLine("Project saved");
        Task task = new Task(new Action(LogDiff));
        task.Start();
        Console.ReadLine();
    }

    public void LogDiff()
    {
        var results = GetDiff("Processing Diff");
        Console.WriteLine(results);
    }

推荐阅读