等待任务完成后未发生继续委托的执行

时间:2018-11-02 16:25:22

标签: c# android xamarin.android

在下面的完整,可验证和可运行的代码示例中,方法FireT1AndForgetawaitTask T1退出后({em> BREAKPOINT-将Abort设置为true时(在 BREAKPOINT-2 )永远不会达到1 。

但是,在此模型的实际代码中,执行仍在继续,所以我不确定行为上的差异吗?

注意:调用Task.Delay也不会导致达到 BREAKPOINT-1

注意:在建模(生产)代码中,OnCreateT1退出时返回,这可能会影响连续性。

namespace AsyncAwait
{
    [Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
    public class MainActivity : AppCompatActivity
    {
        public bool Abort { get; set; }

        public Task T1()
        {
            return Task.Run(/*async*/() =>
            {
                while (!Abort) /*BREAKPOINT-2*/
                {
                    //Task.Delay(new TimeSpan(0, 0, 5));
                    Thread.Sleep(5000);
                }
            });
        }

        public async void FireT1AndForget()
        {
            await T1();

            while (true) /*BREAKPOINT-1*/
            {
                lock (_lock)
                {
                    //Task.Delay(new TimeSpan(0,0,2));
                    Thread.Sleep(2000);
                }
            }
        }

        private readonly object _lock = new object();

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            // Set our view from the "main" layout resource
            //SetContentView(Resource.Layout.activity_main);

            FireT1AndForget();

            while (true)
            {
                lock (_lock)
                {
                    //Task.Delay(new TimeSpan(0, 0, 5));
                    Thread.Sleep(5000);
                }
            }
        }
    }
}

0 个答案:

没有答案