views:

105

answers:

4

Hi there,

I recently started programming in WinForms using C#. I have a requirement where I need to search a set of folders and the sub-folders and display the status information to a textbox as I do the search like -

Looking up folder "C:\Windows"...
Found 8 files...
Copying file 1 of 8 to "D:\Temp"...

I have a method which does all the searching and stuff. I don't know how to display the status messages (like above) to a textbox periodically. Currently, the form waits for the method to be complete, and displays the messages all at once. I want them to be displayed one by one as the method progresses.

Thanks in advance.

+1  A: 

use a BackgroundWorkerThread and the ReportStatus function. That way your UI will be responsive while the search takes place.

gbogumil
A: 

Run the method that performs searches on a separate thread (if you're not doing so already). It's quite easy using the async delegate features in .NET.

You can then write to the text box from the worker thread using Control.BeginInvoke() - you must do this because access to UI control sis affinitized to the single UI thread.

You can also create a background worker thread and use the ReportProgress method to notify the UI of updates. There's a fairly complete example of this approach available here that you can download and examine.

LBushkin
+1  A: 

To properly solve this your searching function will need to be running on a background thread. If the searching occurs on the UI thread it will block updates to the display preventing a periodic status message from being displayed.

The easiest way to do this in a WinForms application is to use a BackgroundWorker. It has a minimum of support for running a task on a background and returning progress information to the UI thread. Additionally there are a lot of tutorials available online to get you started with a solution.

JaredPar
A: 

Thank you everyone for your quick responses. I've followed this tutorial for BackgroundWorker and ReportStatus and was able to get it to work just how wanted. You guys are fast!

Ozzy