-2
請點我要如何使用BackgroundWorker的或者什麼,我必須在應用程序做一些用來保持GUI凍結很好的說明漫長的過程?
Gui當我執行ping操作或其他任何操作時會凍結。只是很煩人,我想要顯示Ping不同主機的ping結果,但它會凍結,直到它停止ping列表中的所有主機。
請點我要如何使用BackgroundWorker的或者什麼,我必須在應用程序做一些用來保持GUI凍結很好的說明漫長的過程?
Gui當我執行ping操作或其他任何操作時會凍結。只是很煩人,我想要顯示Ping不同主機的ping結果,但它會凍結,直到它停止ping列表中的所有主機。
這裏是一個example:
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
namespace SL_BackgroundWorker_CS
{
public partial class Page : UserControl
{
private BackgroundWorker bw = new BackgroundWorker();
public Page()
{
InitializeComponent();
bw.WorkerReportsProgress = true;
bw.WorkerSupportsCancellation = true;
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
}
private void buttonStart_Click(object sender, RoutedEventArgs e)
{
if (bw.IsBusy != true)
{
bw.RunWorkerAsync();
}
}
private void buttonCancel_Click(object sender, RoutedEventArgs e)
{
if (bw.WorkerSupportsCancellation == true)
{
bw.CancelAsync();
}
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
for (int i = 1; (i <= 10); i++)
{
if ((worker.CancellationPending == true))
{
e.Cancel = true;
break;
}
else
{
// Perform a time consuming operation and report progress.
System.Threading.Thread.Sleep(500);
worker.ReportProgress((i * 10));
}
}
}
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if ((e.Cancelled == true))
{
this.tbProgress.Text = "Canceled!";
}
else if (!(e.Error == null))
{
this.tbProgress.Text = ("Error: " + e.Error.Message);
}
else
{
this.tbProgress.Text = "Done!";
}
}
private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.tbProgress.Text = (e.ProgressPercentage.ToString() + "%");
}
}
}
BackgroundWorker worker = new BackgroundWorker();
public Form1()
{
InitializeComponent();
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
worker.RunWorkerAsync();//Calls worker_DoWork on a separate thread.
}
void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)//Runs when worker_DoWork is completed.
{
//
}
void worker_DoWork(object sender, DoWorkEventArgs e)
{
//
}
http://msdn.microsoft.com/en-us/library/cc221403(v=vs.95).aspx?ppud=4 – RQDQ 2012-04-19 14:14:45
你可能會從顯示凍結時如何使用它中受益。我從來沒有遇到過這個問題。 – 2012-04-19 14:15:14
http://msdn.microsoft.com/en-us/library/hybbz6ke.aspx – heavyd 2012-04-19 14:16:33