2012-10-21 15 views
0

我正在開發Windows 8的應用程序。我有一個名爲「User」的C#類。用戶有一個稱爲認證的方法。我的方法看起來像這樣:在WinRT中檢測方法的完成時間(C#)

public class User 
{ 
    public bool IsAuthenticated { get; set; } 

    public async void Authenticate(string username, string password) 
    { 
    // Code to build parameters and url is here 
    var response = await httpClient.PostAsync(myServiceUrl, new StringContent(json, String.Text.Encoding.UTF8, "application/json")); 
    JsonObject result = JsonObject.Parse(await response.Content.ReadAsStringAsync()); 
    } 
} 

Authenticate方法的工作原理。它成功擊中我的服務並返回適當的細節。我的問題是,如何檢測此方法何時完成?我在調用這個方法來響應用戶點擊我的應用中的「登錄」按鈕。例如,像這樣的:

private void loginButton_Click(object sender, RoutedEventArgs e) 
{ 
    User user = new User(); 
    user.IsAuthenticated = false; 
    user.Authenticate(usernameTextBox.Text.Trim(), passwordBox.Password.Trim()); 

    if (user.IsAuthenticated) 
    { 
    // Allow the user to enter 
    } 
    else 
    { 
    // Handle the fact that authentication failed 
    } 
} 

本質上,我需要等待authenticate方法來完成其執行。但是,我不知道該怎麼做。我究竟做錯了什麼?

謝謝

回答

1

首先,你需要做出Authenticate()回報Task而不是void
返回的Task(由編譯器生成)將爲您提供有關異步操作狀態的信息。

您還需要製作事件處理程序方法async
然後你可以await你的其他async方法的結果。


一般情況下,你不應該使用async void方法,除非事件處理程序。

相關問題