【问题标题】:Running long synchronous operation asynchronously异步运行长同步操作
【发布时间】:2018-07-16 16:17:10
【问题描述】:

下面我有一个简单的异步示例,它可以正常工作,输出如下:

Starting
Processing Diff
Log Diff Initiated
Diff processed

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

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

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

仅供参考,我使用的是 .net 4.0,这就是为什么我在示例中使用了 Delay 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;
    }
}

【问题讨论】:

  • 为什么不直接使用Task.Run,​​然后忘记它——你并没有真正在等待任何结果,所以我认为不需要异步/等待。
  • 现在怎么不能按预期工作?由于在“Diff 处理”之前打印了“Log diff Initial”,所以它似乎按照您的意愿工作?如果不是,如何不是
  • @MineR 这可能就是我正在寻找的东西,只要它在 .net 4.0 中得到支持。明天试试,让你知道

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


【解决方案1】:

你为什么不在分离任务中执行你繁重的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);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-26
    • 2019-05-27
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多