C# – how to make User Controls to run on their own thread


how can i make a user control to run on its own thread ?

e.g. by following code in a user control , coz user control uses main app thread it make main thread to sleep


Best Solution

User controls need to run on the UI thread because that is a restriction in the Windows API. If you try and use Windows Forms controls from another thread you will get an exception.

You can run other code in another thread, but use the UI thread to update the controls. You can use BackgroundWorker for this. Or you can use the InvokeRequired and Invoke or BeginInvoke methods on the control instance to have it execute code on the UI thread.

You mention you want to use a mutex lock. A mutex is to avoid having multiple threads access a resource at the same time. If all your code is running in the same thread then you don't need a lock at all.