2
我試圖使用後臺工作來顯示任務正在運行並向用戶報告當前進度。在我做了一般的搜索和嘗試簡單的例子之前,從未使用過背景工作。這是我目前陷入困境的地方。我在MSDN上使用這個例子:http://msdn.microsoft.com/en-us/library/cc221403(v=vs.95).aspxBackgroundWorker不報告進度的問題
但是,我試圖用webforms來做到這一點。所以我將頁面的Async屬性設置爲true。問題是它在整個過程中從不更新我的標籤。它只是在最後更新它。下面是代碼:
我創建了一個全球性的BackgroundWorker:
private BackgroundWorker bw = new BackgroundWorker();
在我的Page_Load方法,我有:
bw.WorkerReportsProgress = true;
bw.WorkerSupportsCancellation = false;
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
然後各種方法:
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (!bw.IsBusy) bw.RunWorkerAsync();
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
for (int i = 1; i <= 10; i++)
{
System.Threading.Thread.Sleep(1000);
worker.ReportProgress(i * 10);
}
}
private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
lblProgress.Text = "Processing... " + e.ProgressPercentage.ToString() + "%";
}
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null) lblProgress.Text = "Error Updating: " + e.Error.Message;
}
然而,它在整個過程中從不更新。我在10秒後看到處理... 100%。幫幫我??
UPDATE
最終我能夠生成一個新的線程按照MSDN上的這個例子:http://msdn.microsoft.com/en-us/library/7a2f3ay4(v=vs.90).aspx
如果鏈接出現,以下是完整的示例代碼:
using System;
using System.Threading;
public class Worker
{
// This method will be called when the thread is started.
public void DoWork()
{
while (!_shouldStop)
{
Console.WriteLine("worker thread: working...");
}
Console.WriteLine("worker thread: terminating gracefully.");
}
public void RequestStop()
{
_shouldStop = true;
}
// Volatile is used as hint to the compiler that this data
// member will be accessed by multiple threads.
private volatile bool _shouldStop;
}
public class WorkerThreadExample
{
static void Main()
{
// Create the thread object. This does not start the thread.
Worker workerObject = new Worker();
Thread workerThread = new Thread(workerObject.DoWork);
// Start the worker thread.
workerThread.Start();
Console.WriteLine("main thread: Starting worker thread...");
// Loop until worker thread activates.
while (!workerThread.IsAlive);
// Put the main thread to sleep for 1 millisecond to
// allow the worker thread to do some work:
Thread.Sleep(1);
// Request that the worker thread stop itself:
workerObject.RequestStop();
// Use the Join method to block the current thread
// until the object's thread terminates.
workerThread.Join();
Console.WriteLine("main thread: Worker thread has terminated.");
}
}
謝謝。這是因爲bw_ProgressChanged事件不會強制回傳還是我誤解? – sr28
你說得對。當時整合這些功能的時機並不正確。 –
感謝您的信息。我可能會沿着AJAX路線走下去。 – sr28