C # streams for file management

I need to save the file, unfortunately, it can potentially be very large, so saving it can take several minutes. Since I need to do this from a GUI thread, I don't want to block GUI execution. I was thinking of trying a save operation in a separate thread to allow the main GUI thread to continue executing.

Is there a good (easy) way to create a new stream, save the file and destroy the stream without any unpleasant side effects ?!

I must say that I NEVER had to use streams so that I was a complete beginner! Any help would be greatly appreciated!

+3
source share
5 answers

BackgroundWorker ( ) - , , . A BackgroundWorker , , .

: - , ? , - (!) , , . , , .

+5

, BackGroundWorker, Threading .

+5

, . , , ,

void SaveMyFile(object state)
{
    // SaveTheFile
}

ThreadPool.QueueUserWorkItem( SaveMyFile );

, .

+3

-. , .

- , , , , , . , , .

, BeginWrite/BeginRead EndWrite/EndRead, Stream.

BeginWrite , , . , BeginWrite .

EndWrite .

BeginWrite , , , (, GUI).

using System;
using System.IO;
using System.Text;

class Program
    {
        private static FileStream stream;
        static void Main(string[] args)
        {
            stream = new FileStream("foo.txt", 
                                    FileMode.Create, 
                                    FileAccess.Write);

            const string mystring = "Foobarlalala";
            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] data = encoding.GetBytes(mystring);
            Console.WriteLine("Started writing");
            stream.BeginWrite(data, 0, data.Length, callback, null);
            Console.WriteLine("Writing dispatched, sleeping 5 secs");
            System.Threading.Thread.Sleep(5000);
        }

        public static void callback(IAsyncResult ia)
        {
            stream.EndWrite(ia);
            Console.WriteLine("Finished writing");
        }
    }
}

, , , , . GUI, , .

MSDN , , , backgroundworker ThreadPool.

+3

.

0

Source: https://habr.com/ru/post/1705246/


All Articles