Simon
Simon

Reputation: 111

c# program freezes during read/write

I have a program written in C#, it does a lot of read from files from the disk and then output a few lines of text, not many possibly 100 at tops into a text files.

The program freezes about half way through, I'm new to c# and programming in general from research it seems that I need to use a separate thread from the one that controls the form. Two questions,

  1. Should I used a new thread for the read and a new one for the write or just one for the read function?

  2. What would be the best way of doing this?

I hope this makes sense and I really appreciate your help!

Upvotes: 1

Views: 1377

Answers (2)

CharithJ
CharithJ

Reputation: 47520

BackgroundWorker is the best thing to use here. Here is a good tutorial which describe all of its events and properties.

In brief this is what you should do.

  1. Create a background worker instance and set appropriate properties as you need.
  2. Add all the I/O processing code to the DoWork which will be executed in a separate thread.
  3. Add all the logics that you want to execute after processing I/O operation to the RunWorkerCompleted which will be executed in the main thread. Here you can update your UI or do what ever you want to do in the main thread. (You can access the result through the RunWorkerCompletedEventArgs.Result property)

The most important thing to keep in mind is both ProgressChanged and RunWorkerCompleted events are executing in the main thread where you can update the UI by using the background worker results. Only the DoWork event executing in the Background thread.

Upvotes: 2

zsalzbank
zsalzbank

Reputation: 9857

If the full read must occur before the write, you only need one thread - otherwise, you can use two.

Check this out for a threading example: http://msdn.microsoft.com/en-us/library/aa645740(v=vs.71).aspx

Upvotes: 0

Related Questions