How to Pause without Blocking the UI

前端 未结 2 785
攒了一身酷
攒了一身酷 2021-01-29 03:45

I have a click event which causes the phone to vibrate once a button is clicked. This generally works great, except sometimes the vibration doesnt stop until I completely close

相关标签:
2条回答
  • 2021-01-29 04:06

    .NET wraps this functionality up conveniently in the BackgroundWorker class.

    private void SomeMethod()
    {
        // Create backgroundworker
        BackgroundWorker bw = new BackgroundWorker();
        // Attach event handler
        bw.DoWork += bw_DoWork;
    
        // Run Worker
        bw.RunWorkerAsync();
    }
    
    private void bw_DoWork(object sender, DoWorkEventArgs e)
    {
        // Do background stuff here
    }    
    

    It also has support for progress updates and triggers an event on completion, as far as I know, this functionality extends to windows phone. All of this is covered in the MSDN article.

    I would guess what you want to do is call vibrate in the BackgroundWorker, and you can listen for the RunWorkerCompletedEvent which will fire when it is finished. Also, you can happily pause this "thread" and it will not interfere with the UI.

    0 讨论(0)
  • 2021-01-29 04:10

    You can use asynchrony to prevent blocking the UI. Rather than actually blocking the UI thread you need to schedule an action to happen again 100ms from now. Adding a continutation to a Task.Delay call can do just that:

    void newButton_Click(object sender, EventArgs e)
    {
        Action navigate = () =>
            this.NavigationService.Navigate(new uri("/NewPage.xaml", UriKind.Relate));
        if (Settings.EnableVibration.Value)  //boolean flag to tell whether to vibrate or not
        {
            VibrateController.Default.Start();
            Task.Delay(100).ContinueWith(t =>
            {
                VibrationController.Default.Stop();
                navigate();
            });
        }
        else
            navigate();
    }
    
    0 讨论(0)
提交回复
热议问题