[英]Task.ContinueWith() is not working after the Task.Run()
Im doing with the activity indicator of the xamarin. 我正在使用xamarin的活动指标。 I want to stop the indicator after the product is get. 我想在产品拿到后停止指示器。
protected override void OnAppearing()
{
base.OnAppearing();
if (!_appeared) // Avoid repeat loding
{
activity.IsEnabled = true;
activity.IsRunning = true;
activity.IsVisible = true;
var task = Task.Run(() =>
{
ProductViewData productViewData = new ProductViewData();
products = productViewData.GetProductList("10");
count = 10;
productListView.ItemsSource = products;
});
task.ContinueWith(t =>
{
activity.IsEnabled = false;
activity.IsRunning = false;
activity.IsVisible = false;
});
_appeared = true;
}
}
Thanks for any help. 谢谢你的帮助。
Code like this is a lot easier with async/await: 使用async / await这样的代码要容易得多:
protected override async void OnAppearing()
{
base.OnAppearing();
if (!_appeared) // Avoid repeat loding
{
_appeared = true;
activity.IsEnabled = true;
activity.IsRunning = true;
activity.IsVisible = true;
var products = await Task.Run(() =>
{
ProductViewData productViewData = new ProductViewData();
return productViewData.GetProductList("10");
});
productListView.ItemsSource = products;
activity.IsEnabled = false;
activity.IsRunning = false;
activity.IsVisible = false;
}
}
Although the code is simple and readable, there's a lot going on behind the scenes, particularly around when this method returns, and what thread the code after the await
is run on. 尽管代码简单易读,但是幕后还有很多事情发生,特别是在此方法返回时,以及await
代码在什么线程上运行。 It is well worth reading up on this. 值得一读。
I guess this is what you need. 我想这就是您所需要的。
var task = Task.Run(delegate { Console.WriteLine("Task started!"); })
.ContinueWith(delegate { Console.WriteLine("Task continued"); });
Just wrap what you wanna do as functions and call that functions in your task steps. 只需包装要用作函数的内容,然后在任务步骤中调用该函数即可。 For more information read here . 欲了解更多信息,请点击这里 。
Edit: 编辑:
Since an UI operation is the subject of this question, I thought this code from the page I linked would be more useful. 由于UI操作是此问题的主题,因此我认为我链接的页面中的这段代码会更有用。 This code utilizes UI and background scheduler. 此代码利用UI和后台调度程序。
private void Button1_Click(object sender, EventArgs e)
{
var backgroundScheduler = TaskScheduler.Default;
var uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
Task.Factory.StartNew(delegate { DoBackgroundComputation(); },
backgroundScheduler).
ContinueWith(delegate { UpdateUI(); }, uiScheduler).
ContinueWith(delegate { DoAnotherBackgroundComputation(); },
backgroundScheduler).
ContinueWith(delegate { UpdateUIAgain(); }, uiScheduler);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.