直接上代码
public TaskInfo AutoUpClassTest(AutoUpClassInput input) { if (!string.IsNullOrEmpty(input.TaskId)) { //查询状态 var ts = _cache.Get("_AutoUpClass_" + input.TaskId); if (ts != null) return (TaskInfo)ts; else return new TaskInfo { Status = 2, TaskId = input.TaskId, Msg = "失败" }; } else { //首次 string g = Guid.NewGuid().ToString(); Task.Run(() => { try { //漫长的操作 for (int i = 0; i < 30; i++) { Thread.Sleep(1000); _cache.Set("_AutoUpClass_" + g, new TaskInfo { Status =0, Msg = "执行中", TaskId = g ,Progress=$"{i}/{30}" }); } //设置完成 _cache.Set("_AutoUpClass_" + g, new TaskInfo { Status = 1, Msg = "成功",TaskId = g }); } catch (Exception) { //设置失败 _cache.Set("_AutoUpClass_" + g, new TaskInfo { Status = 2, Msg = "失败" ,TaskId = g }); } }); var cacheEntryOptions = new MemoryCacheEntryOptions() .SetSlidingExpiration(TimeSpan.FromMinutes(10)); //设置查询 var taskInfo = new TaskInfo { Status = 0, Msg = "执行中", TaskId = g }; _cache.Set("_AutoUpClass_" + g, taskInfo, cacheEntryOptions); return taskInfo; } }
执行效果