创建的线程不会与主C#

时间:2017-07-05 20:58:41

标签: c# wpf multithreading

我创建了一个线程,但是在我启动它之后,线程会暂停主进程。该线程从谷歌加载一些图像,但当互联网连接丢失时,用户界面无法使用。

这是主题:

string searchWord = "car photo";
PhotoSearchThread = new Thread(() =>
{
    Thread.CurrentThread.IsBackground = true;
    if (!string.IsNullOrWhiteSpace(searchWord))
    {
        string html = GetHtmlCode(searchWord);
        SearchedImagesUrls = GetUrls(html); 
        this.Dispatcher.Invoke(() =>
        {
            if (SearchedImagesUrls.Count > 0)
            {
                BitmapImage image = new BitmapImage();
                image.BeginInit();
                image.CacheOption = BitmapCacheOption.OnLoad;
                image.UriSource = new Uri(SearchedImagesUrls[0]);
                image.EndInit();
                SelectPhotoImage.Source = image; 
            }
        });
    }
});

PhotoSearchThread.Start();

好的线程应该同时运行,那么为什么这个线程会中断其他线程?

2 个答案:

答案 0 :(得分:3)

Invoke用于在主线程或UI线程上运行代码。专门用于更新UI元素,因为那些元素只能由该线程更新。目前,您拥有可在Invoke中加载图片的代码。相反,您应该只将更新UI的代码部分放在Invoke

PhotoSearchThread = new Thread(() =>
{
    Thread.CurrentThread.IsBackground = true;
    if (!string.IsNullOrWhiteSpace(searchWord))
    {
        string html = GetHtmlCode(searchWord);
        SearchedImagesUrls = GetUrls(html); 

        if (SearchedImagesUrls.Count > 0)
        {
            BitmapImage image = new BitmapImage();
            image.BeginInit();
            image.CacheOption = BitmapCacheOption.OnLoad;
            image.UriSource = new Uri(SearchedImagesUrls[0]);
            image.EndInit();
            this.Dispatcher.Invoke(() =>
            {
                SelectPhotoImage.Source = image; 
            });
        }
    }
});

答案 1 :(得分:0)

我找到了解决方案:

  

1.使用以下内容添加以下内容:using System.ComponentModel;

     

2.Declare后台工作人员:

private readonly BackgroundWorker worker = new BackgroundWorker();
  

3.订阅活动:

worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
  

4.实施两种方法:

private void worker_DoWork(object sender, DoWorkEventArgs e)
{
   // run all background tasks here
}

private void worker_RunWorkerCompleted(object sender, 
                                       RunWorkerCompletedEventArgs e)
{
  //update ui once worker complete his work
}
  

5.只要你需要,就可以运行工作人员。

worker.RunWorkerAsync();

此外,如果您要报告进程进度,则应订阅ProgressChanged事件并在DoWork方法中使用ReportProgress(Int32)来引发事件。还设置如下:worker.WorkerReportsProgress = true;(感谢@zagy)

来源:How to use WPF Background Worker

希望得到这个帮助。