使用CancellationToken而不仅仅是标志有什么好处?

时间:2017-12-24 10:55:18

标签: c#

我有一个使用CancellationToken的应用程序。在主线程上调用一些代码,并将令牌传递给它。在该代码中,它有一个运行的while循环。

我的问题是使用取消令牌的优势是什么,而不仅仅是bool runLoopcode

等标志

这是我的代码:

public partial class App : Application
{
    public static CancellationTokenSource cts;
    public static PhrasesFrame phrasesFrame;

    public App()
    {
        InitializeComponent();
        // This is only created once. Because of this 
        // should I make it read only?
        phrasesFrame = new PhrasesFrame();
    }

public partial class PhrasesPage : ContentPage
{
    public PhrasesFrame phrasesFrame;

    public PhrasesPage()
    {
        InitializeComponent();
    }

    protected override void OnAppearing()
    {
        base.OnAppearing();
        // this method is called whenever the screen is 
        // selected
        App.cts = new CancellationTokenSource();
        phrasesStackLayout.Children.Add(App.phrasesFrame);
    }

    protected override void OnDisappearing()
    {
        base.OnDisappearing();
        // this method is called whenever the screen is 
        // removed from view which happens when I choose
        // another screen to display
        App.cts.Cancel();
        phrasesStackLayout.Children.Remove(App.phrasesFrame);
    }

}

public partial class PhrasesFrame : Frame
{

    public PhrasesFrame()
    {
        InitializeComponent();
        vm = new PhrasesFrameViewModel(this);
        phrasesFrameStackLayout.BindingContext = vm;
        faveIconLabel.Text = FontAwesome.FAHeartO;
        hiddenIconLabel.Text = FontAwesome.FAMinusSquareO;
        AddGestures();
        Device.BeginInvokeOnMainThread(() => ShowCards(App.cts.Token).ContinueWith((arg) => { }));

    }

public async Task ShowCards(CancellationToken ct)
{
   // what's the advantage of doing this instead of 
   // while (App.runLoop == true) {}
   while (!ct.IsCancellationRequested) {

   }

0 个答案:

没有答案