SoFunction
Updated on 2025-03-08

.NET 4.5 Asynchronous IO related examples

In C/S architecture, both traditional winform and wpf may encounter asynchronous operation of files. It's okay to say that the file is small, just write the operation code.

If it is a large file, it is often done asynchronously. Show a progress bar or something on the interface, and use a background worker to do it in the background. Here I will tell you that you support asynchronous IO operations in .NET Framework 4.5. Greatly simplify the previous asynchronous method code.

Using backgroundworker code

Copy the codeThe code is as follows:

View Code

private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            bak = new ();
            += bak_DoWork;
            += bak_RunWorkerCompleted;
            ();         
        }

        void bak_DoWork(object sender, e)
        {
            string sourceDir = @"E:\";
            string endDir = @"F:\";
            foreach (string filename in (sourceDir))
            {
                using (FileStream SourceStream = (filename, ))
                {
                    using (FileStream DestinationStream = (endDir + (('\\'))))
                    {
                        (DestinationStream);
                    }
                }
            }
        }

        void bak_RunWorkerCompleted(object sender, e)
        {
            ("ok");
        }


The above should be the most basic operation, are there many codes? Let’s take a look at the writing of .NET Framework 4.5.
Copy the codeThe code is as follows:

private async void Button_Click_2(object sender, RoutedEventArgs e)
        {
            string sourceDir = @"E:\";
            string endDir = @"F:\";
            foreach (string filename in (sourceDir))
            {
                using (FileStream SourceStream = (filename, ))
                {
                    using (FileStream DestinationStream = (endDir + (('\\'))))
                    {
                        await (DestinationStream);
                    }
                }
            }
            ("ok");
        }

Hope it helps some people.