This question already has an answer here:
I have a method that I am declaring as an asych method. The code is listed below.
private async Task<string> tempPassword()
{
char[] hashes = "ABCDEFGHJKMNPQRUVWXY34689!?@$#".ToCharArray();
Random r = new Random(DateTime.Now.Millisecond);
List<char> bits = new List<char>();
while (bits.Count < 7)
{
int i = r.Next(0, hashes.Length);
if (!bits.Contains(hashes[i]))
bits.Add(hashes[i]);
}
return string.Join("", bits.ToArray());
}
While this code is correct and compiles, Visual Studio gives me the following feedback:
This async method lacks await operators and will run synchroniously. Consider using the await operators to await non-blocking API Calls, or 'await Task.Run(...)' to do CPU-Bound work on a background thread.
While I do not have a wealth of background with async (which is why I am using it, to be honest, so I will learn) it doesn't seem to me like there is anything in this method that would require an await operator so I am a bit kerfuffled as to what it is I am supposed to be awaiting.
it doesn't seem to me like there is anything in this method that would require an await operator
In that case, why is the method async
in the first place? You only need async
if you use await
. In its current state, the method will execute synchronously, and return an already completed Task<string>
. If you don't expect it to ever need to be asynchronous, you can change it's signature to just return string
. If you do expect it to become asynchronous in the future (or if you can't change the return type because you're implementing an interface or overriding a method from the base class), you can remove the async
modifier, and explicitly return a completed task:
return Task.FromResult(string.Join("", bits.ToArray()));
This will avoid the overhead of creating an async state machine.
private string tempPassword()
- shay__