A little more about File.WriteAllBytes

2

How to display a progress by synchronizing the following function:

File.WriteAllBytes(string path, byte[] content);

This method should be called according to a System.Threading.Thread

Ex:

Thread wnd;
string wnd_file;
byte[] wnd_bytes;

void Install(string path, byte[] content){
   wnd_file=path; wnd_bytes=content;
   wnd = new Thread(new ThreadStart(BackgroundProgressTASK));
   wnd.Start();
}

void BackgroundProgressTASK(){
  File.WriteAllBytes(wnd_file, wnd_bytes);
}

So the application will not suffer any crashes during the moment you write the file!

    
asked by anonymous 29.01.2015 / 22:56

1 answer

5

It does not. This method is even blocking. It should perform completely without external interference. You can create thread (and this is neither the most recommended way to do this) that will not resolve. The only way is to create a method that will write little by little where you have control.

The question is a bit confusing. To make the progress indicator it is not necessary to have a thread or other similar mechanism. If you want the entire application to remain free to execute the best way is to use an asynchronicity technique in the whole method that does what you want. See an example in this answer .

Note that trying to run GUI with different threads does not allow you to run GUI on more than one thread . At least not in normal conditions. What you can do is use a BackgroudWorker (has an example of progress indicator). To simplify it would be something like this (I did not test):

var backgroundWorker = new BackgroundWorker(); //estará fora do método de escrita

using (var stream = new FileStream(wnd_file, FileMode.OpenOrCreate)) {
    using (var writer = new BinaryWriter(stream)) {
        var remain = wnd_bytes.Length;
        var written = 0;
        while (remain > 0) {
            var size = Math.Min(4096, remain);
            writer.Write(wnd_bytes, written, size);
            written += size;
            remain -= size;
            backgroundWorker.ReportProgress(written * 100 / wnd_bytes.Length);
        }
    }
}

In the documentation there is an example of how to write a asynchronous write method . But if I understood what you described, you do not need it.

    
29.01.2015 / 23:49