如何在单击新按钮时杀死一个按钮的事件。单击新按钮时杀死一个按钮事件
我有一个事件(按钮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