在我的程序中,有一个带有"打印收据"按钮;点击按钮,我需要只调用一次方法。目前,用户可以打印多个收据,我不知道如何防止这种情况。
private async void PrintReceipt()
{
await _printReceiptInteractor.PrintTerminalReceiptAsync(_receipt).ConfigureAwait(false);
Dispatcher.Dispatch(() => { this.Close(); });
}
如何执行一次只执行此方法的要求?
更新:我设法通过添加一个IsBusy属性和一个方法来解决这个问题,我在那里设置了IsBusy,然后调用该方法,然后我在最终中将IsBusy设置为false一个尝试和捕获声明。
答案 0 :(得分:2)
您需要禁用调用方法的GUI控件,否则您需要创建一个属性,例如bool来跟踪方法的输入。
private bool _executed = false;
private void Method()
{
if(!_executed)
{
_executed = true;
// ...
}
}
private readonly Button _button = new Button();
private void Method()
{
_button.Enabled = false;
// ...
}
private readonly object _lockObj = new object();
private void Method()
{
// Prevent concurrent access
lock(_lockObj)
{
if(!_executed)
{
_executed = true;
// ...
}
}
}
答案 1 :(得分:0)
试试这个:
private bool _printed = false;
private async void PrintReceipt()
{
if(!_printed)
{
await _printReceiptInteractor.PrintTerminalReceiptAsync(_receipt).ConfigureAwait(false);
Dispatcher.Dispatch(() => { this.Close(); });
_printed = true;
}
}
答案 2 :(得分:0)
bool isbusy;
private async void PrintReceipt()
{
isbusy = true
try
{
await _printReceiptInteractor.PrintTerminalReceiptAsync(_receipt)
}
finally
{
//This block will always exeute even if there is an exception
isbusy = false
}
}
打印Command
我在这里有demoe
private ICommand _printCommand;
public ICommand PrintCommand
{
get
{
return _printCommand ??(PrintCommand=
new RelayCommand(async () => await PrintReceipt(), CanExecute));
}
}
//Determine can execute command
private bool CanExecute()
{
return !isbusy;
}
<强>的Xaml 强>
<button Content="Print" Command={Binding PrintCommand"/>
当
Command
无法执行时,即系统忙时,按钮将处于禁用状态。
我建议你阅读MVVM