Reputation: 41
I am trying to make a async timer that will close all opened forms(in a thread-safe way) (apart from BaseWindow
)and open a new LoginScreen
form. Currently all forms are getting closed but when the new LoginScreen
form start, it's UI is frozen.
The code looks like this:
{
public static Form[] OpenForms
{
get
{
Form[] forms = null;
int count = Application.OpenForms.Count;
forms = new Form[count];
if (count > 0)
{
int index = 0;
foreach (Form form in Application.OpenForms)
{
forms[index++] = form;
}
}
return forms;
}
}
delegate void CloseMethod(Form form);
static private void CloseForm(Form form)
{
if (!form.IsDisposed)
{
if (form.InvokeRequired)
{
CloseMethod method = new CloseMethod(CloseForm);
form.Invoke(method, new object[] { form });
}
else
{
form.Close();
}
}
}
static public void CloseAllForms()
{
// get array because collection changes as we close forms
Form[] forms = OpenForms;
// close every open form
foreach (Form form in forms)
{
if (form.GetType() != typeof(BaseWindow))
{
CloseForm(form);
}
}
}
private void PollUpdates(object sender, EventArgs e)
{
;
if (Program.Globalsession.SessionId != default(Guid))
{
if (DateTime.Compare(Program.Globalsession.ValidTo, DateTime.Now) < 0)
{
CloseAllForms();
var login = new LoginScreen();
login.Show();
}
}
}
public BaseWindow()
{
InitializeComponent();
var login = new LoginScreen();
login.Show();
var theTimer = new System.Timers.Timer(5000);
theTimer.Elapsed += PollUpdates;
theTimer.Start();
}
}
Any idea what am I doing wrong?
Upvotes: 0
Views: 347