0

I have written the below code-snippet in Main method. I'm not able to use await keyword before WriteAsync().

snippet-1:

while (fileLength < 100)
            {
                i = i + 1;
                sampleText = String.Format("Line {0} of {1} \n", i, lineCount);
                data = encoding.GetBytes(sampleText);
                fileStream.WriteAsync(data, 0, data.Length);
                fileLength = fileLength + data.Length;
                Console.WriteLine("Length of file written: " + fileLength);
            }
 fileStream.Close();

snippet-2:

while (fileStream1.Position == fileLength)
            {
                 fileStream1.ReadAsync(data, 0, 100);
            }

The connection is closed in snippet-1 after the execution of while loop and snippet-2 is working fine.

while executing it I have got the following queries:

  1. Is it mandatory to use await operator before WriteAsync(Byte[], Int32, Int32)?
  2. Can we use ReadAsync(Byte[], Int32, Int32) without any await operator?
  3. Can we use Thread.Sleep in place of await operator?

I have little experience in C# and multi-threading. Can any one help me in getting understand on the above queries?

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
Divya
  • 1
  • 1
  • 1
    case you are using .net core 3 or later you can change the main method to work with async operations, just change the void with async Task – spzvtbg Feb 27 '22 at 07:58
  • you can use async void too for older versions – spzvtbg Feb 27 '22 at 07:58
  • 1. No, but then it won't do what you want, it won't wait. 2. Yes, but it won't do what you want 3. No, it does something different. In short: yes, no, no, respectively. Side points: you should use a proper `using` block, and in modern versions of C# you can do `await using` which call `DisposeAsync` – Charlieface Feb 27 '22 at 11:42
  • Does this answer your question? [How and when to use ‘async’ and ‘await’](https://stackoverflow.com/questions/14455293/how-and-when-to-use-async-and-await) – Charlieface Feb 27 '22 at 11:43

1 Answers1

0
  1. you can create an wrap method and .GetAwaiter().GetResult() inside Main eg.
public void Main()
{
   MainWrap().GetAwaiter().GetResult();
}
private async Task MainWrap()
{
    await SomeStuff();
}
  1. you can simply use public async Task Main() as the entrypoint (it's almost the same as first solution)

and for the reason, you simply think async await it a syntactic sugar for SoThingsWithoutWait(Func<objct> onDoneCallback), the async keyword is for mark thecontext will generate those callback (they are actully a state machine that for create a new Task base on your await chain ) and the await keyword is an mark for create an "state" inside the state machine.
so without the async keyword and an "awaitable type" , you can not genreate the state machine code.

John
  • 716
  • 1
  • 7
  • 24