c# - 异步运行长同步操作
问题描述
下面我有一个简单的异步示例,它可以按照我的预期使用以下输出:
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;
}
}
解决方案
为什么不在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);
}
推荐阅读
- amazon-web-services - 尝试配置 aws s3 触发器以在两者位于同一区域但不同的 aws 帐户时调用 lambda 函数
- android - 登录屏幕没有弹出
- sql - 从数据库中随机选择一定比例的所有客户
- javascript - 受限导航 React Router Dom - 私有和公共路由
- java - JVM 8 SIGSEGV:可能是什么原因?
- python - Circuitpython“交互式”选项
- java - 使用 Spring Boot 允许 MySQL 中的重复值
- node.js - Discord.js - 不使用客户端 EventEmitter 无法获取通道属性
- c++ - 函子上显式转换函数的基本原理
- php - php , 从 excel 转换为日期