2016-07-22 38 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