Haider Ali
Haider Ali

Reputation: 2795

How to make 2 forms on 2 separate threads in C# winform application

I am developing an interface in my C# 4.0 winform application, to fire some sms in bulk. Each message content is different so that I have to fire messages one by one. I have a form from where the end user can shoot smss, it may be more than a thousand.

I want to manage a queue. If the user shoots a sms then it will be submitted to the queue and the queue will send sms one by one.

So I have to create a form to manage the queue. The problem is that I want my application to work normally and in the background the queue sends sms.

So how can I achieve this task? I have tried BackGroundWorker, but I don't know how to maintain a separate thread with a form.

Upvotes: 0

Views: 1450

Answers (3)

Boppity Bop
Boppity Bop

Reputation: 10473

you have to create one thread (called worker thread) which runs for the life your application.

you have to have a queue or even better a concurrent queue http://msdn.microsoft.com/en-us/library/dd267265.aspx

the worker thread wait when an item (sms) appears in the queue, takes that item and do its work.

the UI is completely decoupled from that work.

this is most basic use of the class Thread.

Background worker is least suitable solution. obviously you can use a washing machines to build a house but most people use bricks.

Upvotes: 1

Kelqualyn
Kelqualyn

Reputation: 509

You can start Thread then create new instance of form on it (with no parent) and then start message loop (such code located in Main method of project's template). Remember, any form (generally any GDI object) can be used only on thread that creates it. E.g you can't create child form on another thread, then parent's. Every GUI thread must run message loop.

Upvotes: 0

Richard Schneider
Richard Schneider

Reputation: 35477

All forms must be on the UI thread. The sending of the SMS should be performed by the BackgroundWorker.DoWork event. The updating of the form is then done by BackgroundWorker.RunWorkerCompleted event.

The UI thread is main thread of the application for SWF (winforms)

If you are using C# 4.0 or above, you may also want to investiage the Take Parallel Library (http://msdn.microsoft.com/en-us/library/dd460717.aspx). But I would first get BackgroundWorker implementation to work. Then use TPL to send simultaneous SMS. Could really speed things up.

Upvotes: 2

Related Questions