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;
}