2017-10-18 176 views
0

enter image description here事件處理程序的C#異步空了警告/錯誤

我理解的異步不應使用void的返回類型,除非它是一個事件處理程序。但我有上面的代碼片段,當我打開警告作爲我的項目設置中的錯誤時,我編譯代碼時出現上述錯誤。

RECS0165異步方法「」不應該返回void

如果我刪除async然後我再編譯錯誤

的「伺機」運算符只能異步拉姆達內使用 表達。考慮用'async'修飾符標記此lambda表達式。

建議的修復方法是將async添加到匿名函數。這是一個死鎖。

我在這裏做錯了什麼?

重現該問題的步驟:

  • 創建VS2017空白UWP項目,它會創建應用程序,XAML和MainPage.xaml中。
  • 添加以下代碼在MainPage.xaml.cs中

    命名空間APP4 { 使用系統; using System.Threading.Tasks; 使用Windows.ApplicationModel.Core;使用Windows.UI.Core的 ;使用Windows.UI.Xaml的 ; using Windows.UI.Xaml.Controls;

    public sealed partial class MainPage : Page 
    { 
        private DispatcherTimer refreshTimer; 
    
        public MainPage() 
        { 
         this.InitializeComponent(); 
    
         this.refreshTimer = new DispatcherTimer() 
         { 
          Interval = new TimeSpan(0, 0, 30) 
         }; 
    
         refreshTimer.Tick += async (sender, e) => { await DisplayMostRecentLocationData(string.Empty); }; 
        } 
    
        private async Task DisplayMostRecentLocationData(string s) 
        { 
         await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,() => 
         { 
    
         }); 
        } 
    } 
    

    }

+0

的委託不正確。 'async(sender,e)=>'或使用'EventArg'派生的類用於'e' – Nkosi

回答

3

Tick事件處理程序委託不正確。

使用

async (sender, e) => ... 

或使用EventArg派生類e

async (object sender, EventArgs e) => ...  

什麼你目前擁有的是你正在試圖將其指派爲事件處理程序的匿名對象。編譯器不允許這個錯誤。

+0

將代碼更改爲'this.refreshTimer.Tick + = async(sender,e)=> {await this。DisplayMostRecentLocationData(的String.Empty); };'但仍然是相同的編譯錯誤。或'this.refreshTimer.Tick + = async(object sender,EventArgs e)=> {await this.DisplayMostRecentLocationData(string.Empty); };同樣的編譯錯誤。 – hardywang

+0

@hardywang什麼是編譯錯誤 – Nkosi

+0

@hardywang,鑑於我不知道你的Display ...方法是否使用'refreshTimer.Tick + = async(sender,e)=> {0}來測試它等待Task.Run (()=> {}); ()=> {};}和'refreshTimer.Tick + = async(object sender,EventArgs e)=>等待Task.Run(()=> {}); };'它編譯得很好。 – Nkosi