0

请看以下代码:

foreach(string url in urls)
{
  //Method that will process url ProcessUrl(url)
  //Add eached proccessed url to a treelist
}

ProcessUrl 方法有 HttpWebRequest 和 HttpWebResponse 所以有时它需要轻推,如果有很多链接,它会花费一些时间来挂起我的程序。

我实际上不能提出一个解决方案,因为我可能基于一些错误所以我想要的是让这段代码运行,同时我可以在我的程序中 100% 运行而不会出现任何崩溃或挂起,并且每个新处理后的链接将被插入到树列表中,没有任何延迟。

4

1 回答 1

2

如果您想在后台执行长时间运行的操作,并在操作结果可用时将其传递回 UI,同时 UI 保持响应,那么在这里使用BackgroundWorker很简单。

    void BeginExpensiveOperation()
    {
        var worker = new BackgroundWorker();
        worker.WorkerReportsProgress = true;
        worker.DoWork += ExpensiveWork;
        worker.ProgressChanged += WorkerOnProgressChanged;

        List<string> urls = new List<string> { "http://google.com" };
        worker.RunWorkerAsync(urls);
    }

    // runs in a worker thread
    void ExpensiveWork(object sender, DoWorkEventArgs e)
    {
        var worker = (BackgroundWorker)sender;
        var urls = (List<string>) e.Argument;
        foreach (var url in urls)
        {
            //TODO: do your work here synchronously
            var result = new WebClient().DownloadString(url);

            //TODO: pass the result in the userState argumetn of ReportProgress
            worker.ReportProgress(0, result); // will raise worker.ProgressChanged on the UI thread
        }
    }

    private void WorkerOnProgressChanged(object sender, ProgressChangedEventArgs progressChangedEventArgs)
    {
        //this executes on the UI thread
        var value = progressChangedEventArgs.UserState;
        //TODO: use result of computation to add it to the UI
        panel.Children.Add(new TextBlock {Text = value.ToString()});
    }

在占位符中填写您的问题特定代码//TODO:并调用BeginExpensiveOperation()以异步启动操作。

于 2013-02-02T08:41:02.317 回答