Windows Forms: thread safe access to GUI? - windows

in the last hours I've struggled with delegates and accessing Windows Forms controls (C++) where I've used this tutorial (the first thread safe method): http://msdn.microsoft.com/en-us/library/ms171728.aspx#Y190
Changing TextBoxes and Labels works perfectly but when I want to show or hide the whole GUI from another thread this fails.
I use the following methode (which is part of the GUI class):
System::Void UI::showUI(boolean value) {
if (this->InvokeRequired) {
SetTextDelegate^ d = gcnew SetTextDelegate(this, &UI::showUI);
this->Invoke(d, gcnew array<Object^> { value });
} else {
if (value == true)
this->Show();
else
this->Hide();
}
}
In the first call the if-clause is true so Invoke is called. But usually the showUI method should be called a second time automatically where the if-clause returns false, but this is not happening. So the GUI is neither shown nor hiden.
Is it necessary to show/hide the GUI with a delegate or can I do it from every possible thread? If a delegate is necessary, why is showUI not executed a second time?
Thanks,
Martin
edit: okay the name SetTextDelegate is not appropriate but this is not the point...

This is a pretty standard case of deadlock, not uncommon with Control::Invoke(). It can only proceed if the UI thread is not busy. Use Debug + Windows + Threads and double-click the Main thread. Look at the call stack to see what it is doing. The typical case is that it is blocking, waiting for the thread to finish the job. That will never happen since the thread can't complete until the Invoke() call returns.
Don't block the UI thread.
Consider using BackgroundWorker, its RunworkerCompleted event is nice to do stuff after the thread completes, removing the need to block.

Related

Async table creation and query advantages / disadvantages

In my application I have the following:
db2.CreateTable<CategoryGroup>();
db2.CreateTable<Category>();
db2.CreateTable<CategoryGroupSource>();
db2.CreateTable<CategorySource>();
db2.CreateTable<Phrase>();
db2.CreateTable<PhraseSource>();
db2.CreateTable<Score>();
db2.CreateTable<Setting>();
From what I understand there is an Async way to do this also:
database.CreateTableAsync<TodoItem>().Wait();
Can someone explain if there is any advantage in me using the Async way and do people normally always use the Async?
Also are there likely to be benefits if I use this type of Async query:
public Task<TodoItem> GetItemAsync(int id)
{
return database.Table<TodoItem>().Where(i => i.ID == id).FirstOrDefaultAsync();
}
When calling the methods on the main (UI) thread everything on the UI stops for as long as it takes that method to execute. If db2.CreateTable<CategoryGroup>() doesn't take up much time when doing it's thing, it shouldn't be a problem.
Doing a lot of time consuming actions straight after each other might affect your UI and make it freeze.
Calling the *Async variant of the method moves the work to a background thread, via the task API. Calling Wait() on that task, though, makes the current thread (in this case the UI thread) wait for the task to finish, and you're stuck with the same problem.
You should always await tasks: await database.CreateTableAsync<TodoItem>(). This will let it execute on a background thread and not make the current thread wait for it to finish. The next line in your code won't be executed until the Task is finished though. When you write the code, it makes the `Async variant look like it's behaving like the regular version.
Personally, I'd probably move all the methods into a task and just await that. That way you're not returning to the UI thread between each task to execute the next one:
await Task.Run(() =>
{
db2.CreateTable<CategoryGroup>();
db2.CreateTable<Category>();
db2.CreateTable<CategoryGroupSource>();
db2.CreateTable<CategorySource>();
db2.CreateTable<Phrase>();
db2.CreateTable<PhraseSource>();
db2.CreateTable<Score>();
db2.CreateTable<Setting>();
}
In this case you're making the database do all it's work on a background thread (and not freezing the UI while it's doing it). It then returns the result to the UI thread to enable you to update UI.
public Task<TodoItem> GetItemAsync(int id)
{
return database.Table<TodoItem>().Where(i => i.ID == id).FirstOrDefaultAsync();
}

How does another program/process interrupt the execution of my program?

Lets say I have written a very simple program in an operating system which supports UI. My program looks like below:-
#include <os_specific_ui.h>
int main()
{
// Create a button using os specific API
object my_button = add_button("I am a button");
// Register for a mouse down call back on that button
mouse_down_handler = register_mouse_down_cb(my_button, func_to_be_called_on_mouse_down);
// do something...
// have a lot of functions which keep calling each other for a long period of time
}
void func_to_be_called_on_mouse_down(void)
{
print("my_button got clicked");
}
The program is clearly a single threaded program. When I run it, it keeps on doing something. In the mean time if there is a mouse down event, then callback registered for it will get hit and start executing.
I want to know how can another process (which handles mouse movements) can call a function in my process? And what happens to the state of my process when such a callback is hit. I mean my program was doing something when callback was hit. So it just stops doing that and starts executing callback or what? And what after the callback function finishes executing? Does my program go back to do whatever it was doing before callback was hit?
Pretty much all GUI programs run some form of event/main loop. That is, as the last part in main() it enters a loop, which reads events from the OS, and dispatches those events to your callback handlers and performs other tasks to realize the GUI.
i.e. the code you have in // have a lot of functions which keep calling each other just isn't possible unless you do that in a separate thread. Your own execution flow isn't stopped and taken over by some other process.
A GUI program is more or less done like this:
#include <os_specific_ui.h>
void func_to_be_called_on_mouse_down(void)
{
print("my_button got clicked");
}
int main()
{
// Create a button using os specific API
object my_button = add_button("I am a button");
// Register for a mouse down call back on that button
mouse_down_handler = register_mouse_down_cb(my_button, func_to_be_called_on_mouse_down);
for (;;) {
Event e
read_event_from_OS(&e);
handle_event(&e);
}
}
Where read_event_from_OS() fetches mouse/keyboard/redraw/etc. events from the operating system, and handle_event() figures out what to do with that event, such as redraw a window, or call one of the callback functions that your program has registered.
If the OS you're working on does things differently, you'll have to tell us more about it

Windows Phone Mutex issue

I made some researches about mutexes, but could not find anything to worth to clarify what I want as much as I can understand. I can use mutexes on linux easily. But I don't know why my mutexes won't work on my application. I also looked for some examples, and implemented it. But no way;
Here is my mutex initilaziation;
public static Mutex mutex = new Mutex(true,"mut");
Here I used my mutex to lock;
private void button4_Click(object sender, RoutedEventArgs e) //Challenge Start/Stop
{
StartLocationService(GeoPositionAccuracy.High);
mutex.WaitOne();
mutex.WaitOne();
MessageBox.Show("I'm in mutex");
///...
}
I did this just to see if mutex is cared by my application. But no ways, my application shows "IM in mutex" message without getting any release signal from somewhere. Normally, there must be a deadlock, but no.
What I'm trying to do is, before StartLocationService fully completed, I don't want the message to appear. I also tried mutex.ReleaseMutex(); within end of StartLocationService function. But it did not work too.
I wish semaphores had existed in WP.
Please help me; Thanks
You have no deadlock because you passed 'true' for the first parameter of the Mutex, which means that the mutex is initially owned by the thread who created it. That is, your main thread.
For your example, what you must do is set the constructor's parameter to False, then call mutex.WaitOne(). This should effectively block your main thread. Then, call mutex.ReleaseMutex() at the end of the StartLocationService method.
Now that's for the theory. I wouldn't recommend you to do that, because the main thread is the UI thread. It means that the UI will become unresponsive until the location service has finished initializing, which is awful UX. You should rather display some kind of loading screen, and hide it at the end of the StartLocationService method.
Note that you can use a ManualResetEvent instead of a mutex. The end result will be the same, but it might be a tad more intuitive to use.

Can someone explain callback/event firing

In a previous SO question it was recommended to me to use callback/event firing instead of polling. Can someone explain this in a little more detail, perhaps with references to online tutorials that show how this can be done for Java based web apps.
Thanks.
The definition of a callback from Wikipedia is:
In computer programming, a callback is
executable code that is passed as an
argument to other code. It allows a
lower-level software layer to call a
subroutine (or function) defined in a
higher-level layer.
In it's very basic form a callback could be used like this (pseudocode):
void function Foo()
{
MessageBox.Show("Operation Complete");
}
void function Bar(Method myCallback)
{
//Perform some operation
//When completed execute the callback method
myCallBack().Invoke();
}
static int Main()
{
Bar(Foo); //Pops a message box when Bar is completed
}
Modern languages like Java and c# have a standardized way of doing this and they call it events. An event is simply a special type of property added to a class that contains a list of Delegates / Method Pointers / Callbacks (all three of these things are the same thing. When the event gets "fired" it simply iterates through it's list of callbacks and executes them. These are also referred to as listeners.
Here's an example
public class Button
{
public event Clicked;
void override OnMouseUp()
{
//User has clicked on the button. Let's notify anyone listening to this event.
Clicked(); //Iterates through all the callbacks in it's list and calls Invoke();
}
}
public class MyForm
{
private _Button;
public Constructor()
{
_Button = new Button();
//Different languages provide different ways of registering listeners to events.
// _Button.Clicked += Button_Clicked_Handler;
// _Button.Clicked.AddListener(Button_Clicked_Handler);
}
public void Button_Clicked_Handler()
{
MessageBox.Show("Button Was Clicked");
}
}
In this example the Button class has an event called Clicked. It allows anyone who wants to be notified when is clicked to register a callback method. In this case the "Button_Clicked_Handler" method would be executed by Clicked event.
Eventing/Callback architecture is very handy whenever you need to be notified that something has occurred elsewhere in the program and you have no direct knowledge of when or how this happens.
This greatly simplifies notification. Polling makes it much more difficult because you are responsible for checking every so often whether or not an operation has completed. A simple polling mechanism would be like this:
static void CheckIfDone()
{
while(!Button.IsClicked)
{
//Sleep
}
//Button has been clicked.
}
The problem is that this particular situation would block your existing thread and have to continue checking until Button.IsClicked is true. The nice thing about eventing architecture is that it is asynchronous and let's the Acting Item (button) notify the listener when it is completed instead of the listener having to keep checking,
The difference between polling and callback/event is simple:
Polling: You are asking, continuously or every fixed amount of time, if some condition is meet, for example, if some keyboard key have been pressed.
Callback: You say to some driver, other code or whatever: When something happens (the keyboard have been pressed in our example), call this function, and you pass it what function you want to be called when the event happens. This way, you can "forget" about that event, knowing that it will be handled correctly when it happens.
Callback is when you pass a function/object to be called/notified when something it cares about happens. This is used a lot in UI - A function is passed to a button that is called whenever the button is pressed, for example.
There are two players involved in this scenario. First you have the "observed" which from time to time does things in which other players are interested. These other players are called "observers". The "observed" could be a timer, the "observers" could be tasks, interested in alarm events.
This "pattern" is described in the book "Design Patterns, Elements of Reusable Object-Oriented Software" by Gamma, Helm, Johnson and Vlissides.
Two examples:
The SAX parser to parse XML walks
trough an XML file and raises events
each time an element is encountered.
A listener can listen to these
elements and do something with it.
Swing and AWT are based on this
pattern. When the user moves the
mouse, clicks or types something on
the keyboard, these actions are
converted into events. The UI
components listen to these
events and react to them.
Being notified via an event is almost always preferable to polling, especially if hardware is involved and that event originates from a driver issuing a CPU interrupt. In that case, you're not using ANY cpu at all while you wait for some piece of hardware to complete a task.

Modal operation using IMessageFilter and DoEvents

This is a Windows Forms application. I have a function which captures some mouse events modally till a condition is met. For example, I would like to wait for the user to select a point in the window's client area (or optionally cancel the operation using the Escape key) before the function returns. I am using the following structure:
Application::AddMessageFilter(someFilter);
while(someFilter->HasUserSelectedAPoint_Or_HitEscapeKey()){
Application::DoEvents();
}
Application::RemoveMessageFilter(someFilter);
This works quite nicely except for taking up nearly 100% CPU usage when control enters the while loop. I am looking for an alternative similar to what is shown below:
Application::AddMessageFilter(someFilter);
while(someFilter->HasUserSelectedAPoint_Or_HitEscapeKey()){
// Assuming that ManagedGetMessage() below is a blocking
// call which yields control to the OS
if(ManagedGetMessage())
Application::DoEvents();
}
Application::RemoveMessageFilter(someFilter);
What is the right way to use IMessageFilter and DoEvents? How do I surrender control to the OS till a message is received? Any GetMessage equivalent in the managed world?
You could sleep the thread for 500ms or so between DoEvents() calls. Experiment with different values to see what feels right.

Resources