Background thread, async and GUI (dlangui)

evilrat evilrat666 at gmail.com
Mon Jul 11 09:32:46 UTC 2022


On Sunday, 10 July 2022 at 09:15:59 UTC, Bagomot wrote:
> Based on Thread, I managed to do what I intended. I have not 
> yet been able to figure out how to do the same through the Task.
>
> Here in the example, when you click on the Start button, a 
> worker is launched that updates the progress bar.
>
> ...
>
> Do you have any suggestions how to do it more beautifully and 
> not through the Thread? In particular, I would like to see the 
> comments of the dlangui developers (@GrimMaple).

Since you've already used `executeInUiThread` you can now just 
move your Thread.run() implementation to a free function and run 
it using task instead.
`executeInUiThread` will ensure that passed delegate will be 
called in UI thread making it safe to call from another thread or 
task.

Not sure about default widgets, but in some cases for your custom 
properties you might need to `invalidate()` widget to trigger 
redraw.

Anyway you will need a reference to your widget to update 
progress bar value, options are:
- It can be done in place where you start your task (e.g. inside 
button click event, delegates can access call site scope)
- get widget reference directly by using 
`getWidgetById("WIDGET_ID")` (or how it was called, though you 
will need to assign ID to your progress bar and remember it)
- use signal-slot mechanism (you still need widget reference to 
bind events)


btw, have you tried googling this forum? I think there was exact 
same question with curl & dlangui a year or two ago, maybe it has 
an answer or at least tips you need?

Anyway for curl notify progress delegate you can just do it 
inside that delegate using `executeInUiThread` there.

like in example here 
https://dlang.org/library/std/net/curl/curl.on_progress.html
adjusting to somewhat above will now look like (not tested)

```d
// download button click event
void downloadbutton_Click()
{
   auto progressBar = (get progress bar reference);

   Curl curl;
   curl.initialize();
   curl.set(CurlOption.url, "http://dlang.org");
   curl.onProgress = delegate int(size_t dltotal, size_t dlnow, 
size_t ultotal, size_t ulnow)
   {
     // even though onProgress can be run in another thread this 
delegate will be run on next UI tick
     executeInUiThread( (){ progressBar.setProgress(dlnow/dltotal 
* 100); } );
     return 0;
   };
   curl.perform();
}
```


More information about the Digitalmars-d-learn mailing list