Background thread, async and GUI (dlangui)

Bagomot bagomot at gmail.com
Sun Jul 10 09:15:59 UTC 2022


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.

```d
import dlangui;
import core.thread;
import std.conv;

class MyWorker : Thread {
     private {
         bool _status;
         int _counter;
         Window _window;
     }

     this(Window window) {
         super(&run);
         counter = 1;
         _window = window;
     }

     public void run() {
         _status = true;

         while (_status) {
             _window.executeInUiThread(() {
                 
_window.mainWidget.childById!ProgressBarWidget("progressbar")
                     .progress(_counter * 10);
             });
             _window.update(true);
             _counter++;
             Thread.sleep(3000.msecs);
         }
     }

     public void stop() {
         _status = false;
         _counter = 1;
     }

     public bool status() {
         return _status;
     }
}

class MyWidget : VerticalLayout {
     private {
         Button _btnStart;
         Button _btnStop;
         ProgressBarWidget _progressBar;
         MyWorker _worker;
     }

     this(string id, Window window) {
         super(id);
         styleId = id;

         _worker = new MyWorker(window);

         _btnStart = new Button("btn_start", "Start"d);
         _btnStop = new Button("btn_stop", "Stop"d);
         _progressBar = new ProgressBarWidget("progressbar");
         _progressBar.animationInterval(100);

         _btnStart.click = delegate(Widget src) {

             if (!_worker.status)
                 _worker.start;

             return true;
         };

         _btnStop.click = delegate(Widget src) {
             if (_worker.status)
                 _worker.stop;

             return true;
         };

         addChild(_btnStart);
         addChild(_btnStop);
         addChild(_progressBar);
     }
}

mixin APP_ENTRY_POINT;

extern (C) int UIAppMain(string[] args) {
	
     auto window = Platform.instance.createWindow("Test", null, 
WindowFlag.Resizable, 480, 480);

     auto root = new MyWidget("my_widget");

     window.mainWidget = root;
     window.show();

     return Platform.instance.enterMessageLoop();
}
```

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).


More information about the Digitalmars-d-learn mailing list