Sleep(suspend) and Resuming windows form starts program on worker thread instead of main thread - sleep

The windows form I am working on subscribes to Microsoft.Win32.SystemEvents.PowerModeChanged and on Suspend it runs the Close() method on the form. On Resume it runs the Run() function like it would on initial load. The problem is that when the computer is woken from sleep mode the PowerModeChanged event is triggered on a worker thread named ".Net SystemEvents" and when Run() is called it recreates the form on this worker thread instead of the main thread.
This form is a project I inherited from another developer and I am new to windows form programming. I am wondering if there is a better way to handle the sleep/wake process rather than closing the forms and recreating them on wake or a way to force the creation onto the main thread. Note: If I remove the code and have it do nothing when the computer is slept (suspended) and nothing when it wakes (resumes) then the program continues to work correctly (running on the main thread). Any help will be appreciated. Thanks all.

Capture the UI thread SynchronizationContext in a static field, and Post() on it to go back to the UI thread.

Related

Design pattern for cancelling or ignoring obsolete task on a worker thread

I apologize if there's an obvious answer to this, but I just haven't located it yet.
I'm creating an application that loads some information from a database when the user navigates into an Explorer directory. I'm doing this on a background worker thread (using ATL's CWorkerThread), and calling SetEvent when the navigation occurs. When the background thread is done loading the data, it posts a custom message to a message-only window back on the UI thread. Then the UI thread can do stuff with the loaded info if it wants.
Of course, if the user navigates into a directory, and the worker-thread starts working, but the user quickly navigates away, the current worker-thread task is no longer necessary. So the task should be either cancelled if in progress, or if the worker thread has already posted its completion message to the UI thread, the UI thread should be prepared to check it and ignore it, since it's now stale.
My question is whether there is a nice design pattern and helpful example for this type of situation. I think I've seen situations in which a looping worker thread checks a boolean (like fCancelled) to see if it should still continue doing something. But how about when the completion message is already posted? Is there any standard way in which the worker thread and UI thread can communicate that the message is stale and should be disregarded?
Thank you very much for any input.

Does Go scheduler also manages non-Go Thread created in runtime?

As far as I know, Go runtime scheduler manages some number of OS Threads(probably more than GOMAXPROCS?) and Go routines by assigning Go routines to OS Threads continuously.
So this basically means that the execution of Go routines, including main goroutine , are managed by both of go scheduler and OS' thread scheudling.
Now here's my questions..
Does the execution of goroutine fully managed by OS' thread scheduling if I call runtime.LockOSThread() at the start of that goroutine?
Does the execution of non-Go thread also fully managed by OS' thread scheduling? In other words, if I create a non-Go Thread by CreateThread function (Windows), then the management non-Go Thread's execution is out of scope of Go's runtime scheduler?
What if I launch another goroutine with go func() in that non-Go Thread? How that non-Go Thread and goroutine's execution is managed?
Currently, I'm writing a program in Golang which runs a windows message loop in main() function of go program.
Most of the time it worked well, but sometimes the message loop get blocked and resumed after few seconds and then large amount of old messages get pumped.
(My another question: Windows Message Loop is getting blocked and resumed intermittently (golang))
I had no idea why it occurs, so I suspected main goroutine's OS Thread switch by go scheduler. So I added runtime.LockOSThread() at the start of main() function to ensure windows message loop always run in the same thread.
However, the problem still occured!
I still have no idea why it occurs, but I'm suspecting this is because of Go scheduler because the same logic written in Python 3.4 didn't make any problems like this.
So what I'm trying now is creating a new Windows Thread (non-Go Thread) by calling CreateThread(...) function, and running windows message loop in that thread.
But I'm curious that whether this approach is different with calling runtime.LockOSThread() in main goroutine running windows message loop from Go runtime scheduler's perspective.
So my question is, 'If I create a new non-Go Thread with CreateThread(...) function and run windows message loop in that thread, then does execution of that thread not affected by Go's runtime scheduler?'
Any helps or ideas will be greatly appreciated.
Thanks.
If you run a new OS thread using the CreateThread() routine, Go's scheduler will not touch the thread. However, you will then have to implement a way for that thread to communicate with Goroutines. You can't, for instance, call a Go method directly from the thread created by CreateThread(). Instead, you will have to use some C-based system to poll events from a Goroutine.
As an aside, if you want to run the loop from the main OS thread, you should call LockOSThread() in init() rather than in main(). See https://github.com/golang/go/wiki/LockOSThread:
func init() {
runtime.LockOSThread();
}
func main() {
// Run loop here.
}

MessageBox in worker thread

I have an application which calls into plugin DLLs. Some of those calls are done from a worker thread (i.e. not the UI thread), and just might popup a dialog with MessageBox. According to this (http://www.codeproject.com/Articles/121226/MessageBoxes-and-worker-threads) the effective UI thread is switched to the thread calling MessageBox. This "crashes" the application since the message pump stops receiving messages. Any way to switch back the UI thread to the correct one ? Any work-around ?
The culprit was AttachThreadInput, see this message.

Thread not terminated while application is terminated under Delphi

assume I have a thread which is still running when the application is terminating
(This thread can not terminate because it waits for a Windows api call to return
and that can be long...)
What happens to the thread if the application is closed ?
Can it raise an exception (I'm under Delphi) ?
I'd say that an exception is very plausible. When you call Application.Terminate this will lead to the following sequence of events:
A call to PostQuitMessage.
Application.Terminated being set to True.
Application.Run returning.
System.Halt is called.
Exit procedures are run, specifically DoneApplication which will tear down Application and all components that it owns. Hmm, better hope your thread does not access anything owned by Application.
FinalizeUnits is called. Uh-oh. Memory manager is shut down, and lots more beside.
ExitProcess is called. Now your thread is killed.
Your thread will carry on running until the call to ExitProcess. If it executes any code at all that would be affected by the calls to DoneApplication and FinalizeUnits, then you should expect problems.

creating window in child thread in vc++

I want to create a window and show some image display (like animation based on SetTimer()) on window created using CreateWindow() function. But it should be created on separate thread and should remain alive until user closes this. I tried but was unsuccessful.
EDITED
I just googled I found this link How To Create Windows in a Multithreaded Application but one thing i want to know when Window Procedure get invoked. if it is invoked by system then how i can call it from my child thread.
Windows (represented by HWNDs) in Windows have a thread affinity. Their WindowProc is always invoked in the context of the thread they are created with.
As such, they are a convenient way to serialize calls between threads as the PostMessage and SendMessage APIs can be called from any thread in the application, but the WindowProc will get executed in the context of the original creating thread.
Because WM_TIMER messages posted to message queues are the mechanism by which SetTimer works, again you need to be careful when calling SetTimer in a multithreaded app - The timer messages will be processed by the calling thread (if the hwnd parameter is NULL) or the window's thread.
You also, as a result, have to be careful to put a message loop on every thread that might create windows, or want to process timers.
Keep your user-interface on the main Windows thread. Setting a timer using the Windows API doesn't require an additional thread (as your WndProc will get the timer message WM_TIMER).
Even if you have a long running task to perform that might necessitate the use of an additional thread, keep the window on the main thread, do your work in the worker-thread and post back to the main thread with updates.

Resources