如何在單擊新按鈕時殺死一個按鈕的事件。單擊新按鈕時殺死一個按鈕事件
我有一個事件(按鈕G)正在運行(有一個while循環等待一些輸入)。 我有另一個退出操作按鈕。 現在。 G按鈕的事件正在運行時,我無法點擊任何其他按鈕。 我該如何解決這個問題? 謝謝
嗨,@Grokodile謝謝你的代碼。所以我在這裏評論你的代碼,我應該把我的工作邏輯代碼放在我下面評論的地方嗎? Thans
using System;
using System.ComponentModel;
using System.Threading;
using System.Windows;
using System.Windows.Threading;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private BackgroundWorker _worker;
public MainWindow()
{
InitializeComponent();
}
private void RunButtonClickHandler(object sender, RoutedEventArgs e)
{
_worker = new BackgroundWorker {WorkerSupportsCancellation = true};
_worker.DoWork += BackgroundWorkerTask;
_worker.RunWorkerAsync();
//I should Put my job logic here, right?
}
private void StopButtonClickHandler(object sender, RoutedEventArgs e)
{
if (_worker != null && _worker.IsBusy) _worker.CancelAsync();
//I should Put my job logic here, right?
}
private void BackgroundWorkerTask(object sender, DoWorkEventArgs e)
{
// this runs on the BackgroundWorker thread.
while (_worker.CancellationPending == false)
{
Thread.Sleep(500);
// You have to use the Dispatcher to transfer the effects of
// work done in the worker thread back onto the UI thread.
Dispatcher.BeginInvoke(new Action(UpdateTime), DispatcherPriority.Normal, null);
}
}
private void UpdateTime()
{
// Dispatcher runs this on the UI thread.
timeTextBlock.Text = DateTime.Now.ToString();
}
}
}
不,您應該將自己的'作業邏輯'放在BackgroundWorkerTask或UpdateTime中,只需使用XXXButtonClickHandler方法來啓動和停止執行,請參閱我的編輯 – Grokodile