Khoa
Khoa

Reputation: 263

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);
         }

Upvotes: 1

Views: 917

Answers (1)

TheGeneral
TheGeneral

Reputation: 81573

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

E.g Given

private void GetBraintreeToken()
{ ...

You could

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

Upvotes: 5

Related Questions