使用线程调用代码多个时间?

时间:2013-02-02 07:37:39

标签: c# winforms multithreading

请参阅以下代码:

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

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

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

1 个答案:

答案 0 :(得分:2)

如果您想在后台执行长时间运行的操作并将操作结果传递回UI,同时UI保持响应,则可以直接使用{{3这里。

    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()以异步方式启动操作。