如何处理多任务结束时返回不同类型对象的问题?附异步任务示例
异步任务代码整理与优化建议
看起来你正在实现几个带计时功能的异步任务,我先把你给出的代码整理成规范格式,再分享些实用的优化思路:
原始代码整理
private async Task<List<Places>> GetPlaces() { Stopwatch sw = new Stopwatch(); sw.Start(); var list5 = await GetPlacesTask(); sw.Stop(); Testowybox3.Text = sw.Elapsed.ToString()+" get places times"; return list5; } private async Task<List<Categories>> GetCategories() { Stopwatch sw = new Stopwatch(); sw.Start(); var list5 = await GetCategoriesTask(); sw.Stop(); Testowybox2.Text = sw.Elapsed.ToString()+" get categories times"; return list5; }
代码优化建议
你会发现两个方法里的计时逻辑几乎完全重复,这时候可以把通用逻辑提取成复用方法,减少冗余代码,让后续维护更轻松:
// 通用计时执行方法,封装重复逻辑 private async Task<T> ExecuteTaskWithTiming<T>(Func<Task<T>> taskToExecute, Label resultLabel, string taskDescription) { var stopwatch = Stopwatch.StartNew(); var taskResult = await taskToExecute(); stopwatch.Stop(); resultLabel.Text = $"{stopwatch.Elapsed} {taskDescription} times"; return taskResult; } // 简化后的任务方法,代码更简洁 private async Task<List<Places>> GetPlaces() { return await ExecuteTaskWithTiming(GetPlacesTask, Testowybox3, "get places"); } private async Task<List<Categories>> GetCategories() { return await ExecuteTaskWithTiming(GetCategoriesTask, Testowybox2, "get categories"); }
这样后续再新增类似的异步任务时,直接调用这个通用计时方法就好,不用重复写Stopwatch的初始化、启动、停止逻辑啦。
内容的提问来源于stack exchange,提问作者bc291
相关产品推荐
相关产品推荐

