-2

I am trying to return a string from an async method.The code is below.

public async Task<String> AuthenticateUser(string UserID, string Password)
    {
        String securityToken = String.Empty;

        if (UserID == "qw" && Password == "sa")
        {
            securityToken = await GetUniqueKey();
        }
        return securityToken;
    }

    private async Task<string> GetUniqueKey()
    {
        int maxSize = 8;
        int minSize = 5;
        char[] chars = new char[62];
        string a;
        a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVW XYZ1234567890";
        chars = a.ToCharArray();
        int size = maxSize;
        byte[] data = new byte[1];
        RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
        crypto.GetNonZeroBytes(data);
        size = maxSize;
        data = new byte[size];
        crypto.GetNonZeroBytes(data);
        StringBuilder result = new StringBuilder(size);
        foreach (byte b in data)
        { result.Append(chars[b % (chars.Length - 1)]); }

        string r = await result;
        return r;
    }

The error i face is "StringBuilder doesn't contain a definition for 'Getawaiter'".

Saiful Islam
  • 139
  • 5
  • 16

1 Answers1

1

The clue is in the method definition. You need to return Task<string> but you are trying to return a StringBuilder.

You need to do a couple of things to get this to work:

  1. Convert the StringBuilder to a String. This is simple done by calling ToString() on your result object e.g.

    result.ToString();

  2. Wrap the string you are trying to return in a Task. In your case, the easiest way to do this is to call Task.FromResult e.g.

    return Task.FromResult(result.ToString());

Please note, although this allows you to await the methods you code is really asynchronous as it is not I/O bound. Take a look at this answer about how and why to use async/await.

Simply Ged
  • 8,250
  • 11
  • 32
  • 40