Synchronous / Blocking Application.Invoke () for GTK #

Unfortunately, Application.Invoke() is asynchronous:

 private string ThreadFunction(int i) { string result = null; Gtk.Application.Invoke(delegate { OutputStringToUserInterface("i = " + i.ToString()); result = GetStringFromUserInterface(); }); return result; } 

This means that in this example, ThreadFunction() is executed immediately after calling Application.Invoke() , which probably leads to the undefined state of the result string. - Usually ThreadFunction() will be faster and return with the old value (i.e. null ).


This is a workaround using ManualResetEvent to make Application.Invoke() synchronous:

 private string ThreadFunction(int i) { string result = null; ManualResetEvent ev = new ManualResetEvent(false); Gtk.Application.Invoke(delegate { OutputStringToUserInterface("i = " + i.ToString()); result = GetStringFromUserInterface(); ev.Set(); }); ev.WaitOne(); return result; } 

Thus, ThreadFunction() waits until Application.Invoke() returns, as it would, using WinForms Control.Invoke () .

EDIT: Better Code Code


Now my question is: Is there a better solution (regarding performance / resource consumption)?

+4
source share
2 answers

Well, yes, there is no reason to wait for the delegate to complete to get the correct return value. Fix:

 int result = i + 1; 

And it's nice that OutputStringToUserInterface () will execute asynchronously, assuming you don't call ThreadFunction () so often that it floods the UI thread with requests.

If your real code actually depends on the return value from the function that should run in the user interface thread, then no, you cannot do it faster. Clearly what you really want to avoid.

+2
source

You can encapsulate your current code in a common shell:

 public static void GuiInvoke(Action action) { var waitHandle = new ManualResetEventSlim(); Gtk.Application.Invoke( (s,a) => { action(); waitHandle.Set(); }); waitHandle.Wait(); } public static void BeginGuiInvoke(Action action) { Gtk.Application.Invoke( (s,a) => {action();}); } 
+1
source

Source: https://habr.com/ru/post/1300502/


All Articles