簡體   English   中英

創建的線程不能與主C#同時運行

[英]Created thread does not run simultaneously with main C#

我已經創建了一個線程,但是線程在啟動它后會暫停主進程。 該線程會從Google加載一些圖像,但是當互聯網連接丟失時,用戶界面將無法使用。

這是線程:

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();

好線程應該同時運行,那么為什么該線程會中斷其他線程?

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.添加以下使用: using System.ComponentModel;

2.聲明后台工作人員:

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異步。

worker.RunWorkerAsync();

另外,如果要報告流程進度,則應訂閱ProgressChanged事件並在DoWork方法中使用ReportProgress(Int32)引發事件。 還設置以下內容: worker.WorkerReportsProgress = true; (感謝@zagy)

來源: 如何使用WPF背景工

希望對您有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM