如何在向用户报告进度时创建最干净的代码? [英] How to make the cleanest code when reporting progress to a user?
问题描述
我在过去几个月来一直在努力想出一些干净的代码来向用户报告进度。一切似乎总是归结为:
I've struggled for the last couple of months to come up with some clean code to report progress to a user. Everything always seems to boil down to:
ReportProgress("Starting Task 1");
doTask1();
ReportProgress("Task 1 is done");
ReportProgress("Starting Task 2");
doTask2();
ReportProgress("Task 2 is done");
//etc... where report progress does some form of output to the user.
我的好编程人员尖叫着必须是一个更干净的方式!但我很抱歉。任何想法?
The good coder in me screams "There's got to be a cleaner way!" But I'm stumped. Any thoughts?
:我正在寻找更多的关于建筑信息的信息,而不是具体的实现。
EDIT :: I'm looking more for information on architectural information as opposed to implementation specific. The code given is very oversimplified.
推荐答案
将任务设置为事件流,并且事件处理引擎报告进度。每个事件实例可以有自己的名字,进度报告blurb /模板等,如果你想走得很远
set up your tasks as an event stream, and have the event-processing 'engine' report progress. Each event instance can have its own name, progress-reporting blurb/template, etc. if you want to go that far
如果这是一个经常发生的模式,是值得的基础设施的努力。完成后,可用代码可能如下所示:
if this is a pattern that occurs often, it is worth the effort for the infrastructure. When you're done, the usable code might look something like:
EventQueue tasks = new EventQueue();
tasks.Add(new TaskEvent(this.doTask1,"Foo-ing the bar"));
tasks.Add(new TaskEvent(this.doTask2,"Bar-ing the foo"));
tasks.Add(new TaskEvent(this.doTask3,"Glitching and whinging"));
...
tasks.Execute(this.ProgressEventHandler);
这篇关于如何在向用户报告进度时创建最干净的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!