-1

So a simple application that has a button to get data from a server and then updates a Text in UI. In addition, I want to start another thread that again gets the data every 3 seconds. Is the below code the right way to create a thread and update the UI (binding Value)? Has the usage of the delegate NoArgDelegate a drawback in this scenario? Or is a bad idea to pass an async method in the delegate? I am still trying to get the concept of delegates and Dispatcher.

    private delegate void NoArgDelegate();
    public IAsyncCommand GetDataCommand { get; private set; } // binding for a "Get data" button

    public JustAViewModel()
    {
        // ...
        GetDataCommand = AsyncCommand.Create(() => GetDataAsync());

        var fetcher = new NoArgDelegate(ContinuouslyFetchData);
        fetcher.BeginInvoke(null, null);
    }

    public string Value // in xaml: TextValue="{Binding Value}" 
    {
        get => _value;
        set
        {
            if (_value != value)
            {
                _value = value;
                RaisePropertyChanged("Value");
            }
        }
    }

    private async void ContinuouslyFetchData()
    {
        while (true)
        { 
            System.Threading.Thread.Sleep(3000);
            await GetDataAsync();
        }
    }

    private async Task<string> GetDataAsync()
    {
        Value = await Task.Run(() => DataProvider.GetData());
        return Value;
    }
gts13
  • 1,048
  • 1
  • 16
  • 29

1 Answers1

1

You have misunderstood what BeginInvoke does. It does not create a new thread.

However, you should not create a thread anyway. For a cyclically repeated action, use a timer.

I'd recommend a DispatcherTimer, with an async Tick event handler:

private readonly DispatcherTimer timer;

public JustAViewModel()
{
    timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(3) };
    timer.Tick += TimerTick;
    timer.Start();
}

private async void TimerTick(object sender, EventArgs e)
{
    Value = await Task.Run(() => DataProvider.GetData());
}
Clemens
  • 123,504
  • 12
  • 155
  • 268