2

I have a relatively long process in C-Sharp (30 seconds to 2 minutes depending on the network its running on...) that causes my UI to white screen while it runs. How would I go about fixing this? Do I need to assign the tasks its own thread? If so, can you please point me to a good resource on that?

coderego
  • 33
  • 4

6 Answers6

5

Take a look at the BackgroundWorker component.

Michael Minton
  • 4,447
  • 2
  • 19
  • 31
  • 1
    To add a little more context, this is a tool which will cause work to be done on a separate thread, like the other answers have suggested. – Rex Morgan May 06 '11 at 16:46
1

Yes, you need to run off of the UI Thread. The UI Thread is a single thread that can only perform one action at a time. If it's processing your code, then it is not redrawing controls or otherwise updating the rest of the GUI.

See: .NET threading solution for long queries

Community
  • 1
  • 1
pickypg
  • 22,034
  • 5
  • 72
  • 84
1

If you are using WinForms, then you could use the BackgroundWorker component: http://fernandof.wordpress.com/2007/04/04/implementing-multi-threading-in-winforms-using-the-backgroundworker-class/

Or create a new Thread to do the processing.

CodingWithSpike
  • 42,906
  • 18
  • 101
  • 138
1

As stated by McMinton and others you could use the BackgroundWorker for this. Alternatively you could also have a look at the Task Parallel Library.

See: http://msdn.microsoft.com/en-us/library/dd537609.aspx

Pelto
  • 76
  • 3
0

Yep, you shall create a new thread for the long running method. Very simple example: http://www.java2s.com/Code/CSharp/Thread/illustratesthecreationofthreads.htm

d.lebedev
  • 2,305
  • 19
  • 27
0

Does your long process need to interact with the user?

If it does, be aware that only the GUI thread can access GUI components on the screen - so your worker thread cannot (say) update a progress bar or status text directly.

However, C# provides the useful "Invoke" method which allows you to automatically switch thread back to the GUI thread to update something on the screen.

I mention it because it isn't always obvious how to find these things in the documentation, and knowing the method name in advance can help.

Nikki Locke
  • 136
  • 1
  • 3
  • Nikki, this is exactly what I need. Would you be able to provide some more information? I would like to display a progress bar. Would you recommend using the background worker, creating a thread, or using a thread pool? – coderego May 06 '11 at 18:03
  • Nikki, this is exactly what I need. Would you be able to provide some more information? I would like to display a progress bar. Would you recommend using the background worker, creating a thread, or using a thread pool? To add some information, The use case is to run 1 process at a time (these are long processes) and use the output of one as input to the next with some user interaction in between each step. I'd like each process to update a progress bar. – coderego May 06 '11 at 18:08