I am trying to make a thread class. The class simply creates a thread of the new form to open
class Threading
{
private static int sendingForm;
public void StartThread()
{
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(ThreadProc));
t.SetApartmentState(System.Threading.ApartmentState.STA);
t.Start();
}
public static void ThreadProc()
{
switch (sendingForm)
{
case 1:
System.Windows.Forms.Application.Run(new MainForm());
break;
case 2:
System.Windows.Forms.Application.Run(new ReportPicker());
break;
}
}
}
The idea is simple, I am just practicing using threads. I don’t want to do it in each form, so I tried recycling a bit of code by making it in a class. As you can see, the way I detect the form I want to go is by sending a number depending on the form I want to go. Based on that number will be the form the thread runs. I want to better this if it’s possible. I was thinking of maybe a way to send as parameter the form that I want to go to, but since each form is it’s own type, I can’t find a way to do it. As a matter of fact, I don’t know if it’s possible to do. So, I ask here if you can help me make my code better. It doesn’t matter if it’s by the method I’m asking, just to recycle as much code as possible. This is for the sake of learning to use threads. Thanks to anyone who can help me.
Ok, you want to cut out the redundancy and duplication in ThreadProc. That’s good! Here is a possible solution:
Or, reflection-based:
Or, caller-injected:
Note, that the caller has to change in all cases to adopt the new calling convention.