在下面的完整,可验证和可运行的代码示例中,方法FireT1AndForget
至await
版Task
T1
退出后({em> BREAKPOINT-将Abort
设置为true时(在 BREAKPOINT-2 )永远不会达到1 。
但是,在此模型的实际代码中,执行仍在继续,所以我不确定行为上的差异吗?
注意:调用Task.Delay
也不会导致达到 BREAKPOINT-1 。
注意:在建模(生产)代码中,OnCreate
在T1
退出时返回,这可能会影响连续性。
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);
}
}
}
}
}