如何使用WPF后台工作进程

dgenwo3n  于 2022-11-18  发布在  其他
关注(0)|答案(4)|浏览(338)

在我的应用程序中,我需要执行一系列初始化步骤,这些步骤需要7-8秒才能完成,在此期间,我的UI变得没有响应。为了解决这个问题,我在一个单独的线程中执行初始化:

public void Initialization()
{
    Thread initThread = new Thread(new ThreadStart(InitializationThread));
    initThread.Start();
}

public void InitializationThread()
{
    outputMessage("Initializing...");
    //DO INITIALIZATION
    outputMessage("Initialization Complete");
}

我读过一些关于BackgroundWorker的文章,以及它如何让我的应用程序保持响应性,而不必编写线程来执行冗长的任务,但我还没有成功地尝试实现它,有人能告诉我如何使用BackgroundWorker来实现吗?

bkhjykvo

bkhjykvo1#

1.添加使用

using System.ComponentModel;

1.声明Background Worker

private readonly BackgroundWorker worker = new BackgroundWorker();

1.订阅事件:

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

1.实作两个方法:

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
}

1.在需要时运行worker async。

worker.RunWorkerAsync();

1.跟踪进度(可选,但通常很有用)
a)订阅ProgressChanged事件并在DoWork中使用ReportProgress(Int32)
B)设置worker.WorkerReportsProgress = true;(将信用额度设置为@zagy)

vtwuwzda

vtwuwzda2#

您可能还想考虑使用Task而不是后台工作线程。
在您的示例中,最简单的方法是Task.Run(InitializationThread);
使用任务而不是后台工作线程有几个好处。例如,.net 4.5中新的async/await特性使用Task进行线程化。

jvidinwx

jvidinwx3#

using System;  
using System.ComponentModel;   
using System.Threading;    
namespace BackGroundWorkerExample  
{   
    class Program  
    {  
        private static BackgroundWorker backgroundWorker;  

        static void Main(string[] args)  
        {  
            backgroundWorker = new BackgroundWorker  
            {  
                WorkerReportsProgress = true,  
                WorkerSupportsCancellation = true  
            };  

            backgroundWorker.DoWork += backgroundWorker_DoWork;  
            //For the display of operation progress to UI.    
            backgroundWorker.ProgressChanged += backgroundWorker_ProgressChanged;  
            //After the completation of operation.    
            backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;  
            backgroundWorker.RunWorkerAsync("Press Enter in the next 5 seconds to Cancel operation:");  

            Console.ReadLine();  

            if (backgroundWorker.IsBusy)  
            { 
                backgroundWorker.CancelAsync();  
                Console.ReadLine();  
            }  
        }  

        static void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)  
        {  
            for (int i = 0; i < 200; i++)  
            {  
                if (backgroundWorker.CancellationPending)  
                {  
                    e.Cancel = true;  
                    return;  
                }  

                backgroundWorker.ReportProgress(i);  
                Thread.Sleep(1000);  
                e.Result = 1000;  
            }  
        }  

        static void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)  
        {  
            Console.WriteLine("Completed" + e.ProgressPercentage + "%");  
        }  

        static void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)  
        {  

            if (e.Cancelled)  
            {  
                Console.WriteLine("Operation Cancelled");  
            }  
            else if (e.Error != null)  
            {  
                Console.WriteLine("Error in Process :" + e.Error);  
            }  
            else  
            {  
                Console.WriteLine("Operation Completed :" + e.Result);  
            }  
        }  
    }  
}

此外,请参考以下链接,您将了解Background的概念:
http://www.c-sharpcorner.com/UploadFile/1c8574/threads-in-wpf/

u0njafvf

u0njafvf4#

我发现这个(WPF Multithreading: Using the BackgroundWorker and Reporting the Progress to the UI. link)包含了@Andrew的答案中缺少的其余细节。
我发现非常有用的一件事是工作线程不能访问MainWindow的控件(在它自己的方法中),但是当在主窗口事件处理程序中使用委托时,这是可能的。

worker.RunWorkerCompleted += delegate(object s, RunWorkerCompletedEventArgs args)
{
    pd.Close();
    // Get a result from the asynchronous worker
    T t = (t)args.Result
    this.ExampleControl.Text = t.BlaBla;
};

相关问题