简体   繁体   中英

Xamarin Forms - C# - Async and Await Not Working?

I'm struggling with async and await methods in C#.

I want to make sure my "clientToken" variable is populated before proceeding with the API call.

I then put an await method in front of the function 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?)

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 .

Returns a string which contains all authorization and configuration information your client needs to initialize the client SDK to communicate with Braintree.

To your question

I want to make sure my "clientToken" variable is populated before proceeding with the API call.

All you need to do is remove the await , strings are not an awaitable and the function returns synchronously and immediately

Also note, there is nothing to await in your method GetBraintreeToken so it doesn't need the async keyword or return a Task .

If you would like to run it asynchronously , you can call it from Task.Run() in your constructor or page OnAppearing event

Eg Given

private void GetBraintreeToken()
{ ...

You could

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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