我有一个每次执行一个任务的列表,我的问题是当当前任务失败时如何停止待处理的任务?
这是我的代码:
if(await App.TodoManager.CheckContactsData(host, database, domain, contact) != 'failed)'{
if(await App.TodoManager.CheckRetailerOutletData(contact)){
//And so on
}
}
我要执行的操作是想添加某种检查任务是否已成功执行的方法:
if(await App.TodoManager.CheckContactsData(host, database, domain, contact) == "ok"){
//execute another task then check again if the task ok then proceed until the end of the task
}
这是我的示例任务,当重试变量等于FALSE时,不应执行挂起的任务:
public async Task CheckContactsData(string contact)
{
try
{
var getcontactschanges = Constants.conn.QueryAsync<ContactsTable>("SELECT * FROM tblContacts WHERE Supervisor = ? AND LastUpdated > LastSync AND Deleted != '1'", contact);
var contactchangesresultCount = getcontactschanges.Result.Count;
Preferences.Set("contactschanges", contactchangesresultCount.ToString(), "private_prefs");
}
catch (Exception ex)
{
Crashes.TrackError(ex);
var retry = await App.Current.MainPage.DisplayAlert("Checking Retailer Error", "Checking retailer failed.\n\nDo you want to retry? \n\n Error:\n\n" + ex.Message, "Yes", "No");
if (retry)
{
await CheckContactsData(contact);
}
else {
//Pending task should be stop
}
}
}
答案 0 :(得分:0)
您可以通过这种方式
//for Task cancellation
var tokenSource = new CancellationTokenSource();
await App.TodoManager.CheckContactsData(host, database, domain, contact,tokenSource);
await App.TodoManager.CheckRetailerOutletData(contact,tokenSource);
await App.TodoManager.CheckCAFData(contact,tokenSource);
await App.TodoManager.CheckCAFActivityData(contact,tokenSource);
await App.TodoManager.CheckEmailRecipientData(contact,tokenSource);
您必须在每种方法中添加一个类型为CancellationTokenSource的新参数。
public async Task CheckContactsData(string contact,CancellationTokenSource cts)
{
try
{
var getcontactschanges = Constants.conn.QueryAsync<ContactsTable>("SELECT * FROM tblContacts WHERE Supervisor = ? AND LastUpdated > LastSync AND Deleted != '1'", contact);
var contactchangesresultCount = getcontactschanges.Result.Count;
Preferences.Set("contactschanges", contactchangesresultCount.ToString(), "private_prefs");
}
catch (Exception ex)
{
cts.Cancle();
Crashes.TrackError(ex);
var retry = await App.Current.MainPage.DisplayAlert("Checking Retailer Error", "Checking retailer failed.\n\nDo you want to retry? \n\n Error:\n\n" + ex.Message, "Yes", "No");
if (retry)
{
await CheckContactsData(contact);
}
else {
//Pending task should be stop
}
}
}
然后,您必须在每个cts.Cancle();
中致电catch
,
然后您可以像检查
if(!tokenSource.Token.IsCancellationRequested){
//execute another task then check again if the task ok then proceed until the end of the task
}
我希望这会对您有所帮助。