2016-07-22 40 views
2

在我的程序中有一个带有“打印收据”按钮的屏幕;点击按钮,我需要调用一次方法一次。目前,用户可以打印多份收据,但我不知道如何防止这种情况发生。如何制作只执行一次的方法?

private async void PrintReceipt() 
{ 
    await _printReceiptInteractor.PrintTerminalReceiptAsync(_receipt).ConfigureAwait(false); 
    Dispatcher.Dispatch(() => { this.Close(); }); 
} 

我怎么能强制执行只有一次这种方法的要求是什么?

更新:我设法通过增加一个IsBusy物业和在哪里我设置IsBusy有一个方法来解决这个问题,而只是调用该方法,然后我用try和catch设置IsBusy为False 最后原因IM声明。

+4

添加一个布尔'布尔_alreadyPrinted'将其设置为TRUE;如果你打印的文件。在你的方法中检查它是否为'true',如果是'return'。 –

回答

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; 
      // ... 
     } 
    } 
} 
0

试试这个:

private bool _printed = false; 

private async void PrintReceipt() 
{ 
    if(!_printed) 
    { 
     await _printReceiptInteractor.PrintTerminalReceiptAsync(_receipt).ConfigureAwait(false); 
     Dispatcher.Dispatch(() => { this.Close(); }); 

     _printed = true; 
    } 
} 
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

+0

嘿嘿,谢谢,你的回答是更容易理解和明确的,我刚开始作为一个初级开发,现在,IM仍然困惑的代码库,已那里有 “this._printReceiptCommandLazy =新的懒惰(()=>新DelegateCommand (PrintReceipt,CanPrintReceipt));“ 和孤单已经命令 “私人懒 _printReceiptCommandLazy; 公众的ICommand PrintReceiptCommand { 获得{ 回报this._printReceiptCommandLazy.Value; }} ” 我如何能在这里实现你的建议?感谢 – Reaper

+0

继承人的CanPrintReceipt方法 “私人布尔CanPrintReceipt(){ 回报_receipt = NULL;! }” – Reaper

+0

你不需要使用相同的代码库,我建议你可以用你的'ICommand'随便去'CanPrintReceipt'将命令添加到您的用户按钮它将开始工作 – Eldho