我正在使用BackgroundWorker
線程調用一個小例程,它接收來自MSMQ的消息,一旦消息到達MSMQ隊列(消息到達msmq,每隔5秒)它涉及到我的應用程序這是使用BackgroundWorker
線程。以下是我的Win Form類。我是線程的新手,所以如果我做錯了什麼,請請諒解BackgroundWorker線程不會停止winforms c#
問題:我的應用程序是MDI應用程序,當我第一次執行我的應用程序時,它工作得很好,一收到MSMQ消息,隊列,這是每5秒,但是當我關閉這個表單時,它是一個子表單,它關閉的很好,但是在打開同樣的表單後,我正在接收來自MSMQ的消息,並持續了10秒的達賴,所以這意味着我正在搞亂一些東西在後臺工作線程中,我試圖取消這個後臺工作線程,但是我失敗了,無法正確地執行或終止線程。請幫助並分享您的體驗。下面是我的表單代碼。
public partial class FrmBooking : BookingManager.Core.BaseForm.BaseForm
{
internal const string queName = @"messageServer\private$\Response";
private Int32 counter = 0;
BackgroundWorker backgroundWorker1 = new BackgroundWorker();
public FrmBooking()
{
InitializeComponent();
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.WorkerSupportsCancellation = true;
backgroundWorker1.RunWorkerCompleted+=new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
backgroundWorker1.ProgressChanged+=new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
backgroundWorker1.DoWork+=new DoWorkEventHandler(backgroundWorker1_DoWork);
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker bgWorker = sender as BackgroundWorker;
if (bgWorker.CancellationPending)
{
e.Cancel = true;
return;
}
try
{
MessageQueue messageQueue = null;
if (MessageQueue.Exists(queName))
{
messageQueue = new MessageQueue(queName);
}
else
{
MessageQueue.Create(queName);
}
messageQueue.Formatter = new XmlMessageFormatter(new Type[] { typeof(String) });
System.Messaging.Message msg = messageQueue.Receive();
bgWorker.ReportProgress(100, msg);
}
catch (Exception ex) { }
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (!e.Cancelled)
{
backgroundWorker1.RunWorkerAsync();
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
System.Messaging.Message msg = e.UserState as System.Messaging.Message;
listBoxControl1.Items.Add(msg.Body.ToString());
counter++;
labelControl1.Text = String.Format("Total messages received {0}", counter.ToString());
}
private void FrmBooking_Load(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
}
是的,當我關閉窗體我想說backgroundworker.cancelasync(),但此行的事幫助。你是對的參考是一些如何活着,不知道我怎麼能阻止它...仍然嘗試 – Shax 2011-12-18 09:44:23