简体   繁体   English

Xamarin Forms - C# - Async 和 Await 不起作用?

[英]Xamarin Forms - C# - Async and Await Not Working?

I'm struggling with async and await methods in C#.我正在努力使用 C# 中的async 和 await方法。

I want to make sure my "clientToken" variable is populated before proceeding with the API call.我想确保在继续 API 调用之前填充了我的“clientToken”变量。

I then put an await method in front of the function gateway.ClientToken.Generate();然后我在函数gateway.ClientToken.Generate();前面放了一个await方法gateway.ClientToken.Generate(); but it's returning an error:但它返回一个错误:

Error CS1061: 'string' does not contain a definition for 'GetAwaiter' and no accessible extension method 'GetAwaiter' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)错误 CS1061:“string”不包含“GetAwaiter”的定义,并且找不到接受“string”类型的第一个参数的可访问扩展方法“GetAwaiter”(您是否缺少 using 指令或程序集引用?)

Here's my code:这是我的代码:


public Braintree()
        {
            InitializeComponent();
            Task task = GetBraintreeToken();
        }

private async Task GetBraintreeToken()
        {
            var gateway = new BraintreeGateway
            {
                Environment = Environment.SANDBOX,
                MerchantId = "xxxx",
                PublicKey = "xxx",
                PrivateKey = "xxxx"
            };

            var clientToken = await gateway.ClientToken.Generate();

            Result<PaymentMethodNonce> result_nonce = gateway.PaymentMethodNonce.Create(clientToken);
         }

Disregarding any other problem, Generate just returns a string .不考虑任何其他问题, Generate只返回一个string

Returns a string which contains all authorization and configuration information your client needs to initialize the client SDK to communicate with Braintree.返回一个字符串,其中包含您的客户端初始化客户端 SDK 以与 Braintree 通信所需的所有授权和配置信息。

To your question对于你的问题

I want to make sure my "clientToken" variable is populated before proceeding with the API call.我想确保在继续 API 调用之前填充了我的“clientToken”变量。

All you need to do is remove the await , strings are not an awaitable and the function returns synchronously and immediately所有你需要做的是去除await字符串是不是awaitable和函数返回同步,并立即

Also note, there is nothing to await in your method GetBraintreeToken so it doesn't need the async keyword or return a Task .另请注意,您的方法GetBraintreeToken没有任何内容可await ,因此它不需要async关键字或返回Task

If you would like to run it asynchronously , you can call it from Task.Run() in your constructor or page OnAppearing event如果你想异步运行它,你可以在你的构造函数或页面OnAppearing事件中从Task.Run()调用它

Eg Given例如给定

private void GetBraintreeToken()
{ ...

You could你可以

public Braintree()
{
    InitializeComponent();
    Task.Run(() => GetBraintreeToken());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM