如何在不阻塞 UI 的情况下暂停 [英] How to Pause without Blocking the UI

查看:32
本文介绍了如何在不阻塞 UI 的情况下暂停的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个点击事件,一旦点击按钮,手机就会振动.这通常效果很好,除了有时在我完全关闭应用程序之前振动不会停止.我想给应用程序时间来完成它的振动,然后继续该方法的其余部分,但我根本不想阻止 UI.我怎样才能做到这一点

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 the application. I would like to give the application time to complete its vibration and then continue with the rest of the method, but I do not want to block the UI at all. How might I accomplish this

MainPage.xaml.cs

MainPage.xaml.cs

void newButton_Click(object sender, EventArgs e)
{
    //Button vibration
    if (Settings.EnableVibration.Value)  //boolean flag to tell whether to vibrate or not
    {
        VibrateController.Default.Start(TimeSpan.FromMilliseconds(100));
        //place vibration stop here?
    }        

    this.NavigationService.Navigate(new uri("/NewPage.xaml", UriKind.Relate)); 
}

我已经尝试过 VibrationController.Default.Stop();但这完全消除了振动.有没有一种方法可以简单地等到振动完成后导航到新页面,或者执行该方法应该执行的任何其他操作?对此实施的任何建议或建议或其他建议?

I have already tried VibrationController.Default.Stop(); but this completely eliminates the vibration all together. Is there a way to simply wait until after the vibration has completed to then navigate to a new page, or do whatever other action the method should perform? Any reccomendations or advice on this implementation or other suggestions?

推荐答案

您可以使用异步来防止阻塞 UI.您需要安排一个动作在 100 毫秒后再次发生,而不是实际阻塞 UI 线程.将延续添加到 Task.Delay 调用可以做到这一点:

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

这篇关于如何在不阻塞 UI 的情况下暂停的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆