c# - Wait until file completely read and then display the result in a rich textbox -
I know that you can not have GUI controls for working in separate threads. On my form load, I would like to read from a text file and then display content in a rich text box. I'm studying in a different thread but later I would like to show this text on my rich textbox, my window still deposits and my loading spinner does not animate.
Private async void PreviewFileForm_Load (Object Sender, EventArgs E) {string fileName = Path. GetFileName (this.filePath); LblFileName.Text = fileName; RichtxtboxPreview.Visible = false; String file resource = wait readFileAsync (this.filePath); RichtxtboxPreview.Text = fileContents; RichtxtboxPreview.Visible = true; SpinnerLoadFile.Visible = false; } Async works & lt; String & gt; ReadFileAsync (string file path) {string s = String.Empty; Wait for the job. ({=} ({StreamReader sr = file.} Using open text (file path) {s = sr.ReadToEnd ();}}); Return s; } What can I do to indicate that my loading time is waiting for reading and then the Rich Text Box shows results?
You can use the async file I / O to do this.
So if you implement your async file reader like this (change the encoding to the right type for your text file; this code is literally copied from the linked Microsoft sample above) :
Private async works & lt; String & gt; ReadFileAsync (string filepath) {(filestream source stream = new file stream (file path, open filemod, file access. Read, file share reader, buffer size: 4096, usage async: true)) {stringbilder sb. = New stringbilder (); Byte [] buffer = new byte [0x1000]; Int numRead; While ((numRead = sourceStream.ReadAsync (buffer, 0, buffer, length))! = 0) {// Use the correct encoding here; You may need encoding.Utf 8 string text = encoding.unicode.greatstring (buffer, 0, MMRD); Sb.Append (text); } Return sb.ToString (); }} You should be able to call this already.
However, sometimes I have strange things when doing stuff on load events.
In some cases, I have fixed such problems by using the BindingWalk () to put the code in a different method and call it by the method of loading, for example: < Pre> private zeros preview fileForm_load (object sender, eventErguesE) {This .invinkwoke (new action (IOT)); } Private async zero doIt () {string fileName = path. GetFileName (this.filePath); LblFileName.Text = fileName; RichtxtboxPreview.Visible = false; String file resource = wait readFileAsync (this.filePath); RichtxtboxPreview.Text = fileContents; RichtxtboxPreview.Visible = true; SpinnerLoadFile.Visible = false; }
Comments
Post a Comment