C# Application Threading - c#

So I am creating an application that will have a splash screen that loads resources, and when complete will load the Main form of the application. In times past I've just let the splash screen own the thread and stay hidden, but I'm toying with the idea of actually letting my Main form be the thread owner, but I'm having trouble transitioning between forms. My current approach is
void main(String[] args)
{
ApplicationContext appContext = new ApplicationContext(new SplashScreen());
appContext.ThreadExit += appContext_ThreadExit;
Application.Run(appContext);
}
place
private void appContext_ThreadExit(object sender, EventArgs e)
{
Application.Run(new MainForm());
}
This give me the error that you can't start a new message loop on the thread. So how do I go about properly executing this transition? Or am I already using the best method by allowing the SplashScreen to own the thread?

Here is what I came up with, but if anyone has a more elegant or proper way to do it feel free to let me know.
bool isLoading = true;
MainForm.OnLoad()
-> creates and runs SplashScreen
MainForm.OnShow()
-> if isLoading is true, re-hide
SplashScreen.LoadingComplete
-> event to signal completion of loading events
MainForm.SplashScreenLoadingComplete
-> handler sets isLoading to false
-> calls Show() this time form will show
I handle the loading in the SplashScreen with a background worker

Related

Formless desktop app - SystemEvents.SessionEnding not working all the time

I have an app that doesn't show any forms most of the time, and I needed it to close by itself when a user was shutting down the system.
So I created a question, and the answer there, SystemEvents.SessionEnding, seemed to work.
At first.
Here is my Program.Main() method:
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
#region Pre-launch stuff
// Are we upgrading from an older version? We need to grab our old settings!
if (Properties.Settings.Default.UpgradeSettings)
{
Properties.Settings.Default.Upgrade();
Properties.Settings.Default.UpgradeSettings = false;
Properties.Settings.Default.Save();
}
// Visual styles
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
#if !DEBUG
// Add the event handler for handling UI thread exceptions to the event.
Application.ThreadException += new ThreadExceptionEventHandler(ErrorHandling.Application_ThreadException);
// Set the unhandled exception mode to force all Windows Forms errors to go through our handler.
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
// Add the event handler for handling non-UI thread exceptions to the event.
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(ErrorHandling.CurrentDomain_UnhandledException);
#endif
// Since we have no forms open we need to watch for the shutdown event; otherwise we're blocking it
SystemEvents.SessionEnding += new SessionEndingEventHandler(SystemEvents_SessionEnding);
// ...
// ...
// ...
Application.Run();
}
The method SystemEvents_SessionEnding runs a method calling Exit(), which in turn runs:
public static void Exit()
{
MessageBox.Show("test");
try
{
IconHandler.SuperNotifyIcon.Dispose();
}
finally
{
Application.Exit();
}
}
And yet, my app blocks shutdown at times. And the message box that I added there doesn't show up.
I can't figure out how such a simple, simple path of execution could fail. But it does, and it's a major irritant for both me and my app's users.
Any ideas? Thoughts to throw around?
EDIT:
Per corvuscorax's answer, I've tried adding a form, but it's acted weird - at first, I had this in the form's code:
ShowInTaskbar = false;
WindowState = FormWindowState.Minimized;
Shown += (sender, e) => Hide();
And modified the Program.Exit() method to close that form, which would run the disposal code as well in the FormClosing event.
It turned out disabling ShowInTaskbar stopped the form from receiving a HWND_BROADCAST message. I've commented out that line now, but even so, I found that shutdown blocking was occurring. Once I clicked a button I made to show the form and tried to shut down again, it completed smoothly.
I would recommend against not having any forms at all.
Just do a normal WinForms application and set the main Form to be hidden and you get all the message processing working as always.
Addendum
As an added bonus of doing it this way, you also get a console for free while developing - by not hiding the main form, you can have an easy output view, simulate input, trigger actions with buttons, all sorts of useful stuff.
Addendum 2
Here's how I normally create invisible main forms. In the forms constructor, add this:
if (!Debugger.IsAttached)
{
// Prevent the window from showing up in the task bar AND when Alt-tabbing
ShowInTaskbar = false;
FormBorderStyle = FormBorderStyle.FixedToolWindow;
// Move it off-screen
StartPosition = FormStartPosition.Manual;
Location = new Point(SystemInformation.VirtualScreen.Right+10, SystemInformation.VirtualScreen.Bottom+10);
Size = new System.Drawing.Size(1, 1);
}
This will hide the window when not running from within the debugger.
Does your code have a message pump?
You need a message pump inside each user interface thread of your application so that any windows messages aimed at your application are dispatched and processed. Even if you never show a Form on the screen if the thread is a user interface thread when it will still be sent other system messages that would need to be dispatched and processed.
In a typical WinForms applications the message pump is inside this call...
Application.Run(new MyForm());
...which only exits once the MyForm instance is closed. In your case it seems you never make a call to the Application.Run method or anything similar. In which case your not handling windows messages. So what is your processing loop when you are not showing a Form?

.NET Splash screen issues

I have a splash screen for my C# database application that is called via the Shown event. The splash screen contains some information that is preprocessed when the main form's constructor is called, hence why I'm using the Shown event, because that information should be available.
However, when the splash screen is shown, the main form is whited out, and the menu bar, bottom menu bar, and even the gray background are all white and invisible. It looks like the program is hanging, but after the 5 second delay I have built in, the banner goes away and the program is shown normally. Also, on the banner, I have labels that are not shown when the splash screen displays...
Here is my code, some reasoning behind why it isn't working would help greatly.
SPLASH SCREEN CODE :
public partial class StartupBanner : Form
{
public StartupBanner(int missingNum, int expiredNum)
{
InitializeComponent();
missingLabel.Text = missingNum.ToString() + " MISSING POLICIES";
expiredLabel.Text = expiredNum.ToString() + " EXPIRED POLICIES";
}
}
CALLING CODE :
private void MainForm_Shown(object sender, EventArgs e)
{
StartupBanner startup = new StartupBanner(missingPoliciesNum, expiredPoliciesNum);
startup.MdiParent = this;
startup.Show();
Thread.Sleep(5000);
startup.Close();
}
Using startup.ShowDialog() shows the correct label information on the splash screen, but that locks up the application, and I need the splash to go away after about 5 seconds, which is why it's a splash. ;)
First run the splash screen with ShowDialog() instead of Show(), so the splashscreen locks the main form and do not lock the main thread:
private void MainForm_Shown(object sender, EventArgs e)
{
StartupBanner startup = new StartupBanner(missingPoliciesNum, expiredPoliciesNum);
startup.ShowDialog();
}
In the splash screen form you should define a timer that closes the form after 5 seconds:
public partial class StartupBanner : Form
{
private System.Windows.Forms.Timer _closeTimer = new Timer();
public StartupBanner(int missingNum, int expiredNum)
{
this.InitializeComponent();
missingLabel.Text = missingNum.ToString() + " MISSING POLICIES";
expiredLabel.Text = expiredNum.ToString() + " EXPIRED POLICIES";
this._closeTimer = new System.Windows.Forms.Timer();
this._closeTimer.Interval = 5000;
this._closeTimer.Tick += new EventHandler(this._closeTimer_Tick);
this._closeTimer.Start();
}
private void _closeTimer_Tick(object sender, EventArgs e)
{
System.Windows.Forms.Timer timer = (System.Windows.Forms.Timer)sender;
timer.Stop();
this.Close();
}
}
EDIT: Thread.Sleep() locks the whole thread e.g. each action for the forms, so that they cannot handle any message like clicks or button presses. They do not run in background, so it is better to use a timer that can close the form in background.
FIX: removed startup.MdiParent = this; line
It is a feature of Windows, designed to help the user cope with unresponsive programs. When you display the splash screen, Windows sends your main form a message to tell it that it is no longer the active window. This normally causes it to redraw the window caption, using the color for inactive windows. That same message also fires the Form.Deactivated event.
But that doesn't work anymore, your main thread is busy executing code and not going idle to 'pump the message loop'. Windows notices this, the message isn't getting delivered. After a couple of seconds, it replaces your window with the 'ghost window'. It has the same size and border as your main window but with no content, just a white background. And a caption that reads "Not responding". Enough for the user to know that trying to use the window isn't going to work.
Avoid this by using a real splash screen, support for it is already built into .NET.
In your code, MainForm_Shown wait 'Thread.Sleep(5000);', so it got white because the main thread sleep and couldn't get any message. The StartupBanner Form have some reason, too. I suggest you use Thread to avoid sub function or sub thread intercepting main thread and make MainForm whited out.
There is inbuild support for splashscreens in .Net
The best way and using the API is
SplashScreen splash = new SplashScreen("splashscreen.jpg");
splash.Show(false);
splash.Close(TimeSpan.FromMilliseconds(2));
InitializeComponent();

How can I execute code after my form starts?

I'm really new to Windows Forms programming and not quite sure what's the right way to go about programming.
This is my confusion.
I have a single form:
public partial class ReconcilerConsoleWindow : Form
{
public ReconcilerConsoleWindow()
{
InitializeComponent();
SetLogText("Started");
}
public void SetLogText(String text)
{
string logInfo = DateTime.Now.TimeOfDay.ToString() + ": " + text + Environment.NewLine;
tbx_Log.AppendText(logInfo);
}
}
And in my Program.cs class I have the following code:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
ReconcilerConsoleWindow window = new ReconcilerConsoleWindow();
Application.Run(window);
if (CallSomeMethod() == true)
{
window.SetLogText("True");
}
}
}
Now, once the window has been displayed by the Application.Run command, the program halts at that point. How can I do further processing while the window is up?
The above is just an example. My purpose is to read an XMl file and display a datagridview. Subsequently, I watch the XMl file for changes and everytime a change is made, I want to refresh the datagridview. However, once the console pops up, how can i continue with my program and make changes to the information displayed on the form on the fly?
Processing that occurs after Application.Run is usually triggered in the form's Load event handler. You can easily create a Load method in Visual Studio by double clicking any open space on the form.
This would look something like this.
private void ReconcilerConsoleWindow_Load(object sender, EventArgs e)
{
if (CallSomeMethod())
{
this.SetLogText("True");
}
}
The reason this is (as stated in several other answers) is that the main thread (the one that called Application.Run(window)) is now taken up with operating the Message Pump for the form. You can continue running things on that thread through messaging, using the form's or forms' events. Or you can start a new thread. This could be done in the main method, before you call Application.Run(window), but most people would do this in Form_Load or the form constructor, to ensure the form is set up, etc. Once Application.Run returns, all forms are now closed.
Application.Run starts the Windows event handling loop. That loop won't finish til your form closes, at which time anything you do to it won't matter anyway.
If you want to do something with your form, do it in the form's Load event handler.
Program.cs is not meant to have business rules, it should only call your Form and display it. All datagrid loading/refreshing/editing should be done at your Forms. You should be using the Events defined on Forms class, like: OnLoad, OnUnload, OnClose and many others etc.
You are missing the concept. In a Windows Forms Application, your Main Thread is responsible for running the Form.
You can always use more Threads, but in Windows Forms I would recommend using a BackgroundWorker Component for parallel Tasks:
http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx
Or a Timer:
http://msdn.microsoft.com/en-us/library/system.windows.forms.timer.aspx
Once Application.Run(window) is called, you'll want to handle subsequent things within the application window itself.
In the code view of the form, find the following (or add it)
private void ReconcilerConsoleWindow_Load(object sender, EventArgs e)
{
//this is where you do things :)
if (CallSomeMethod() == true)
{
window.SetLogText("True");
}
}

Exception when using secondary UI message pump for a splash screen

I have encountered an odd issue with the way I am showing a splash form, that causes an InvalidAsynchronousStateException to be thrown.
First of all, here is the code for Main{} where I start the splash form:
[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Thread splash = new Thread(new ThreadStart(ShowSplash));
splash.Start();
Application.Run(new MainForm());
}
static void ShowSplash()
{
using (SplashForm splash = new SplashForm())
{
Application.Run(splash);
}
}
I am using .NET2.0, with Win XP.
During some testing where the app was left running for may hours, I noticed that the number of exceptions would occasionally increase by one or two.
(Numbers obtained by PerfMon, viewing '# of Exceps Thrown' counter.) These exceptions seem to be caught and swallowed by the runtime, because they do
not ripple up and cause anything to go wrong in the app itself. At least nothing that I can determine anyway.
I have discovered that the exception is thrown when the UserPreferenceChanged event is fired by the system. Since finding this out, I can generate the exception
at will by changing the background picture or screen saver, etc.
I am not explicitly subscribing to this event myself anywhere in code, but I understand (via the power of Google) that all top level controls and forms subscribe
to this event automatically.
I still have not determined why this event is being fired in the first place, as it appears to happen while the app is running over night, but I guess that is another mystery to be solved.
Now, if I stop the splash form thread from running, the exception disappears. Run the thread, it comes back. So, it appears that something is not unsubscribing from the event, and this is causing the subsequent exception perhaps?
Interestingly, if I substitute my splash form with a default, out of the box Form, the problem still remains:
static void ShowSplash()
{
using (Form splash = new Form())
{
Application.Run(splash);
}
}
While this form is being displayed, any UserPreferenceChanged events do not cause any exceptions. As soon as the form is closed, and the thread exits, exceptions will be thrown.
Further research has lead me to this Microsoft article, that contains the following comment:
Common causes are a splash screens
created on a secondary UI thread or
any controls created on worker
threads.
Hmm, guilty as charged by the looks of it. Note that my app is not freezing or doing anything untoward though.
At the moment, this is more of a curiosity than anything else, but I am conecerned that there may be some hidden nasties here waiting to bite in the future.
To me, it looks like the form or the message pump started by Application.Run is not cleaning up properly when it terminates.
Any thoughts?
Yes, you are running afoul with the SystemEvents class. That class creates a hidden window that listens to system events. Particularly the UserPreferenceChanged event, a lot of controls use that event to know when they need to repaint themselves because the system colors were changed.
Problem is, the initialization code that creates the window is very sensitive to the apartment state of the thread that calls it. Which in your case is wrong, you didn't call Thread.SetApartmentState() to switch to STA. That's very important for threads that display a UI.
Beware that your workaround isn't actually a fix, the system events will be raised on the wrong thread. Your splash thread instead of the UI thread of your program. You'll still get random and extremely hard to diagnose failure when an actual system event gets fired. Most infamously when the user locks the workstation, the program deadlocks when it is unlocked again.
I think calling Thread.SetApartmentState() should fix your problem. Not 100% sure, these UI thread interactions are very difficult to analyze and I haven't gotten this wrong yet. Note that .NET already has very solid support for splash screens. It definitely gets details like this right.
I was able to simulate your problem and I can offer a work around, but there might be a better option out there since this was the first time I had come across this.
One option to avoid the exception is to not actuall close the splash screen, but rather just hide it. Something like this
public partial class SplashForm : Form
{
public SplashForm()
{
InitializeComponent();
}
// Not shown here, this is wired to the FormClosing event!!!
private void SplashForm_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
this.Hide();
}
}
Then it will be important that you make the thread that you run the splash screen on a background thread to ensure that the application is not kept alive by the splash screen thread. So your code would look something like this
[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Thread splash = new Thread(new ThreadStart(ShowSplash));
splash.IsBackground = true;
splash.Start();
Application.Run(new MainForm());
}
static void ShowSplash()
{
using (SplashForm splash = new SplashForm())
{
Application.Run(splash);
}
}

problem with splash screen - C# - VS2005

I have an application.
First I display a splash screen, a form, and this splash would call another form.
Problem: When the splash form is displayed, if I then open another application on the top of the splash, and then minimize this newly opened application window, the splash screen becomes white. How do I avoid this? I want my splash to be displayed clearly and not affected by any application.
You need to display the splash screen in a different thread - currently your new form loading code is blocking the splash screen's UI thread.
Start a new thread, and on that thread create your splash screen and call Application.Run(splash). That will start a new message pump on that thread. You'll then need to make your main UI thread call back to the splash screen's UI thread (e.g. with Control.Invoke/BeginInvoke) when it's ready, so the splash screen can close itself.
The important thing is to make sure that you don't try to modify a UI control from the wrong thread - only use the one the control was created on.
The .NET framework has excellent built-in support for splash screens. Start a new WF project, Project + Add Reference, select Microsoft.VisualBasic. Add a new form, call it frmSplash. Open Project.cs and make it look like this:
using System;
using System.Windows.Forms;
using Microsoft.VisualBasic.ApplicationServices;
namespace WindowsFormsApplication1 {
static class Program {
[STAThread]
static void Main(string[] args) {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
new MyApp().Run(args);
}
}
class MyApp : WindowsFormsApplicationBase {
protected override void OnCreateSplashScreen() {
this.SplashScreen = new frmSplash();
}
protected override void OnCreateMainForm() {
// Do your time consuming stuff here...
//...
System.Threading.Thread.Sleep(3000);
// Then create the main form, the splash screen will close automatically
this.MainForm = new Form1();
}
}
}
I had a similar issue you might want to check out. The Stack Overflow answer I got worked perfectly for me - you may want to take a look.

Categories

Resources