1

假设您有一个辅助方法,该方法执行长时间运行且复杂的数据处理任务,您从后台线程运行,并且您需要该方法的反馈以向用户显示。您认为这些策略中哪一个是最好的方法?

  1. 将委托传递给方法,例如 CrunchData(ShowFeedbackDelegate showFeedback)

  2. 在包含反馈消息的方法期间在某些关键点引发事件(例如,“处理 1 of 100”)。

4

3 回答 3

0

引发事件,这就是事件的目的,记住,事件最终是代表......

于 2013-09-27T10:09:29.693 回答
0

我会用 BackgroundWorker 做到这一点:

        var worker = new BackgroundWorker();
        worker.DoWork += (s, e) =>
        {
            // do something long running
            for (int i = 1; i <= records.Count; i++)
            {
                DisplayMessage("process " + i + " of " + records.Count);
                ProcessRecord(records[i]);
            }
        };

        worker.RunWorkerCompleted+= (s, e) =>
        {
            // report to user
        };

        worker.RunWorkerAsync();
于 2013-09-27T09:57:11.083 回答
0

无需重新发明轮子,使用 TPL。将长时间运行的操作包装在任务中,并使用Task.ContinueWith方法

public Task<MyCustomStatus> LongRunningOperationAsync()
{
    return Task.Factory.StartNew(() => 
                                 {
                                      //Long Running method here
                                      return myCustomStatus;
                                 });
}

和外面

LongRunningOperationAsync().ContinueWith(t=>
                                         {
                                              if(t.Exception == null)
                                              {
                                                 //Something bad happen
                                              }
                                              //Task finished
                                         });

TPL 为您提供足够的灵活性来解决大多数异步问题

于 2013-09-27T09:57:18.890 回答