我是C#和麪向對象編程的新手。我一直在試圖在我的GUI中實現「取消」按鈕,以便用戶可以在進程中停止它。將參數傳遞到backgroundWorker(用作取消按鈕)
我讀到這個問題:How to implement a Stop/Cancel button?並確定backgroundWorker應該是一個很好的選擇,但給出的例子並沒有解釋如何將參數傳遞給backgroundWorker。
我的問題是,我不知道如何將參數傳遞到backgroundWorker,以便它會停止該過程;我只能讓backgroundWorker停下來。
我創建了下面的代碼,試圖瞭解這一點,在我的形式有兩個按鈕(buttonStart和buttonStop)和一個BackgroundWorker(backgroundWorkerStopCheck):
using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Threading;
using System.Timers;
namespace TestBackgroundWorker
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// Set the background worker to allow the user to stop the process.
backgroundWorkerStopCheck.WorkerSupportsCancellation = true;
}
private System.Timers.Timer myTimer;
private void backgroundWorkerStopCheck_DoWork(object sender, DoWorkEventArgs e)
{
//If cancellation is pending, cancel work.
if (backgroundWorkerStopCheck.CancellationPending)
{
e.Cancel = true;
return;
}
}
private void buttonStart_Click(object sender, EventArgs e)
{
// Notify the backgroundWorker that the process is starting.
backgroundWorkerStopCheck.RunWorkerAsync();
LaunchCode();
}
private void buttonStop_Click(object sender, EventArgs e)
{
// Tell the backgroundWorker to stop process.
backgroundWorkerStopCheck.CancelAsync();
}
private void LaunchCode()
{
buttonStart.Enabled = false; // Disable the start button to show that the process is ongoing.
myTimer = new System.Timers.Timer(5000); // Waste five seconds.
myTimer.Elapsed += new ElapsedEventHandler(myTimer_Elapsed);
myTimer.Enabled = true; // Start the timer.
}
void myTimer_Elapsed(object sender, ElapsedEventArgs e)
{
buttonStart.Enabled = true; // ReEnable the Start button to show that the process either finished or was cancelled.
}
}
}
的代碼,如果一切正常,只想在用戶點擊「開始」之前,在重新啓用「開始」按鈕之前坐在那裏五秒鐘,或者如果用戶點擊「停止」,則快速重新激活「開始」按鈕。
有兩個問題與此代碼,我不知道如何處理:
1)「myTimer_Elapsed」方法會導致一個InvalidOperationException當嘗試啓用開始按鈕,因爲「跨線程操作無效「。我如何避免跨線程操作?
2)現在backgroundWorker沒有完成任何事情,因爲我不知道如何向它提供參數,這樣當它被取消時,它會停止計時器。
我很感謝任何幫助!
非常感謝你,丹尼爾。這非常豐富! – Patrigon