异步/等待不工作“字符串不包含定义的GetAwaiter”并且没有扩展名

时间:2016-08-02 19:11:42

标签: c# android xamarin visual-studio-2015 xamarin.android

我在Visual Studio Xamarin中创建Android应用程序,在App的登录屏幕上,当通过Web服务与DataBase建立连接以验证密码时我想显示progressDialog,直到建立连接。

这是onclient方面的代码:

private string login()
{
    string x = null;
    var progress = ProgressDialog.Show(this, "waiting", "Loading");
    progress.SetProgressStyle(ProgressDialogStyle.Spinner);
    new Thread(new ThreadStart(delegate
    {
        RunOnUiThread(async () =>
        {
            x = await services.Verification("abc", "xyz");
            progress.Dismiss();
        });
     })).Start();

    return x;
}

在服务器端:

public string Verification(string userName, string password)
{
    SqlConnection conn = new SqlConnection(@"");
    conn.Open();
    string query = "select category from ACCOUNTS where loginId = '" + userName + "' and pasword= '" + password + "'";
    SqlCommand cmd = new SqlCommand(query);
    cmd.Connection = conn;
    string catagory = null;
    SqlDataReader account = cmd.ExecuteReader();

    if (account.HasRows)
    {
        if (account.Read())
        {
            catagory = account[0].ToString();
        }
    }
    conn.Close();

    return catagory;
}

以下是第x = await services.Verification("abc", "xyz");行的login()函数中的错误,它说:

 'String' does not contain a definition for 'GetAwaiter' and no extension method 'GetAwaiter' accepting a first argument of type 'String' could be found (are you missing a using directive or an assembly reference?)

1 个答案:

答案 0 :(得分:1)

要使用它:

x = await services.Verification("abc", "xyz");

您必须使用以下API:

public async Task<string> Verification(string userName, string password)

但是,您使用什么与数据库进行通信?看起来您直接直接调用Verification方法,而不是通过REST调用服务。在部署应用程序时直接调用该方法不起作用...您需要使用带有async / await,RestSharp或本教程中定义的其他方法的HttpClient调用Web服务的代理:https://developer.xamarin.com/guides/cross-platform/application_fundamentals/web_services/

取自here

var httpClient = new HttpClient();
Task<string> contentsTask = httpClient.GetStringAsync("http://xamarin.com"); 

string contents = await contentsTask;