问题
If I open a Form named FormX that does some processing on its public (not static) variable "Var". "Var" is set from a calling form and processed and returned for output. I open it from multiple forms multiple times during execution. All forms are running simultaneously. It works fine because each FormX is opened using a seperate instance of an object from its parent form. But I have a public static class "Abc" in my project which is accessible to all forms and if I add a code:
public static class Abc
{
public static string Open_form(string Var)
{
FormX Obj = new FormX();
Obj.Var = Var;
Obj.Show();
Obj.Process_Var();
Var = Obj.Var;
Obj.Close();
return Var;
}
}
and call it somewhere from the forms (and multiple times) like:
Form1_Load()
{
//Some operations
MessageBox.Show(Abc.Open_form("ABC"));
//Some operations
MessageBox.Show(Abc.Open_form("XYZ"));
}
Form2_Load()
{
//Some operations
MessageBox.Show(Abc.Open_form("123"));
//Some operations
MessageBox.Show(Abc.Open_form("456"));
}
Form1 and Form2 are opened from a main Form as:
Form1 obj1 = new Form1();
obj1.Show();
Form2 obj2 = new Form2();
obj2.Show();
Then will it cause any problem? Will there be any problem in the processing of variable "Var" if two forms call the static call at the same time? One more question, should I call FormX.Dispose();
after FormX.Close();
Why and why not? Any benefit of FormX.Dispose()
?
回答1:
If FormX.Var
is a static
property or field, then yes, there may be issues when it is used by multiple threads or objects at the same time. If FormX.Var
is not static
, then no, there should be no issues.
Rule of thumb: Always call Dispose
on any object that implements IDisposable
. The GC has a means of calling this for you, but it's always the best practice to call it yourself. To facilitate this, use C#'s using
keyword. The syntax below automatically calls Dispose
.
using (FormX Obj = new FormX())
{
...
}
You rarely need to call Close
directly. Looking at your code, it appears that you want to display FormX as a modal form. That is, you want the user to work with the Form and maybe hit an OK button when they're done. Then you're reading off the value of the Var
property to get the information the user has entered. In this scenario, you need to call ShowDialog
instead of Show
. The ShowDialog
call will only return when the form is closed. Calling Close
after ShowDialog
has no effect because the form is already closed.
All told, I believe your code should look like this:
public static string Open_form(string Var)
{
using (FormX Obj = new FormX())
{
Obj.Var = Var;
Obj.ShowDialog();
Obj.Process_Var();
return Obj.Var;
}
}
回答2:
There is nothing in your post that indicates "multithreading", nor that your forms "are running simultaneously". Therefore, you FormX.Var
value is fine.
来源:https://stackoverflow.com/questions/17150298/opening-a-form-multiple-times-from-a-static-class-which-is-called-from-different