System.IO.IOException: 'The process cannot access the file '@.txt' because it is being used by another process.'

后端 未结 6 661
野的像风
野的像风 2021-01-11 13:15

I am new to programming and I have a question. If I have two functions, one creates a text file and writes into it, while the other opens the same text file and reads from i

6条回答
  •  忘掉有多难
    2021-01-11 13:48

    Actually this is not a problem of closing/disposing the stream, File.WriteAllText and File.ReadAllText does that internally.

    The issue is because a wrong use of the async/await pattern. GET is async but never awaited, thus causing function1 to finish and move on to function2 before all content was actually written to the file.

    The way it is written GET is not awaitable because it is async void which should never be used unless you're dealing with event or really know what you're doing.

    So, either remove the use of async/await completely or be async all the way:

    1. Change GET to be awaitable:

      async Task GET(string link, string fileName)
      
    2. await it in the now async function1:

      async Task function1()
      {
          ...
          for (int x = 0; x < fileNames.Count; x++)
          {
              await GET(linki[x], fileNames[x]);
              //System.Threading.Thread.Sleep(6000);
          }
          ...
      
    3. await function1 in the Elapsed event:

      private async void tickTimera1(object source, ElapsedEventArgs e)
      {
          await function1();
          function2();
      }
      

提交回复
热议问题