Skip to content

Instantly share code, notes, and snippets.

@SpacePurr
Created February 14, 2020 07:27
Show Gist options
  • Save SpacePurr/0eefb3bb60bd6edea082cd767c8f97f5 to your computer and use it in GitHub Desktop.
Save SpacePurr/0eefb3bb60bd6edea082cd767c8f97f5 to your computer and use it in GitHub Desktop.
CancellationToken
public class MainViewModel : BaseViewModel
{
private CancellationTokenSource cancellation;
#region mvvm
private string _text;
public string Text
{
get => _text;
set
{
_text = value;
OnPropertyChanged();
}
}
public Command Start { get; set; }
public Command Stop { get; set; }
public MainViewModel()
{
Start = new Command(StartExecute);
Stop = new Command(StopExecute);
}
#endregion
private void StopExecute(object obj)
{
cancellation?.Cancel();
}
private void StartExecute(object obj)
{
MainMethod();
}
public async void MainMethod()
{
cancellation = new CancellationTokenSource();
await SetDataGrid(cancellation.Token);
UpdateMethod();
SerialPortDialog();
}
public Task SetDataGrid(CancellationToken ct)
{
Task task = null;
task = Task.Run(() =>
{
try
{
for (int i = 0; ; i++)
{
//Проверяем, была ли вызвана отмена потока, если да,
//то генерируем исключение отмены потока
if (ct.IsCancellationRequested)
throw new TaskCanceledException(task);
Thread.Sleep(150);
Text = i.ToString();
}
}
catch (TaskCanceledException)
{
MessageBox.Show("Задача была отменена");
}
});
return task;
}
public void UpdateMethod()
{
MessageBox.Show(MethodBase.GetCurrentMethod().ToString());
}
public void SerialPortDialog()
{
MessageBox.Show(MethodBase.GetCurrentMethod().ToString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment