Does the .net framework provides async methods for working with the file-system?

前端 未结 5 1694
离开以前
离开以前 2020-12-29 03:48

Does the .net framework has an async built-in library/assembly which allows to work with the file system (e.g. File.ReadAllBytes, File.WriteA

5条回答
  •  情深已故
    2020-12-29 04:24

    If you have to write a file in a background task you can write it sincronously in an async method.

    static void Main(string[] args)
    {
        Console.WriteLine("1");
        // thread 1, sync
        byte[] dataToWrite = System.Text.ASCIIEncoding.ASCII.GetBytes("my custom data");
        Task.Run(() =>
        {
            Console.WriteLine("2");
            // aspetto un secondo
            System.Threading.Thread.Sleep(1000);
            // thread 2, async code
            System.IO.File.WriteAllBytes(@"c:\temp\prova.txt", dataToWrite);
            Console.WriteLine("2, end");
        });
    
        Console.WriteLine("3, exit");
    
        Console.ReadLine();
        // thread 1
    }
    

    the execution output will be: 1,3,2,2 end

提交回复
热议问题