I have Taskone that requests the active directory and populates the list with results. I set my task so that it can be undone, however, when the cancel is called, the task continues to do its job. I know that a task was canceled when it returns, and actions are performed to complete the return of the task, but the request continues to run in the background, using memory and processing power. A task can be started and canceled again, with each iteration of the task being performed and resource use. How can I cancel a cancellation?
ViewModel
private async Task RunQuery(QueryType queryType,
string selectedItemDistinguishedName = null)
{
StartTask();
try
{
_activeDirectoryQuery = new ActiveDirectoryQuery(queryType,
CurrentScope, selectedItemDistinguishedName);
await _activeDirectoryQuery.Execute();
Data = _activeDirectoryQuery.Data.ToDataTable().AsDataView();
CurrentQueryType = queryType;
}
catch (ArgumentNullException)
{
ShowMessage(
"No results of desired type found in selected context.");
}
catch (OutOfMemoryException)
{
ShowMessage("The selected query is too large to run.");
}
FinishTask();
}
private void CancelCommandExecute()
{
_activeDirectoryQuery?.Cancel();
}
ActiveDirectoryQuery
public async Task Execute()
{
_cancellationTokenSource = new CancellationTokenSource();
var taskCompletionSource = new TaskCompletionSource<object>();
_cancellationTokenSource.Token.Register(
() => taskCompletionSource.TrySetCanceled());
DataPreparer dataPreparer = null;
var task = Task.Run(() =>
{
if (QueryTypeIsOu())
{
dataPreparer = SetUpOuDataPreparer();
}
else if (QueryTypeIsContextComputer())
{
dataPreparer = SetUpComputerDataPreparer();
}
else if (QueryTypeIsContextDirectReportOrUser())
{
dataPreparer = SetUpDirectReportOrUserDataPreparer();
}
else if (QueryTypeIsContextGroup())
{
dataPreparer = SetUpGroupDataPreparer();
}
Data = GetData(dataPreparer);
},
_cancellationTokenSource.Token);
await Task.WhenAny(task, taskCompletionSource.Task);
}
public void Cancel()
{
_cancellationTokenSource?.Cancel();
}
Cancel() a Command, a Button. . , .