I have a Form in which I start a Task to load the content. If the User clicks Cancel this Task needs to be cancelled of course. But it seems I'm doing something wrong. The form never closes and keeps waiting for the task:
public partial class Designer : Form
{
private CancellationTokenSource _cancellationTokenSource;
private Task _loadTask;
private async void Designer_Shown(object sender, EventArgs e)
{
_cancellationTokenSource = new CancellationTokenSource();
try
{
_loadTask= Workbench.Instance.CurrentPackage.LoadObjects(_cancellationTokenSource.Token);
await _loadTask;
}
catch (Exception ex)
{
Debug.Print(ex.ToString());
}
}
private void btnCancel_Click(object sender, EventArgs e)
{
_cancellationTokenSource.Cancel();
_loadTask.Wait(); //Waits forever
this.DialogResult = DialogResult.Cancel;
this.Close();
}
}
Where's my fault?
Edit
The Code Of LoadObjects()
public Task LoadObjects(CancellationToken cancelToken)
{
return Task.Run(() =>
{
LoadParameters(cancelToken);
LoadConditionChecks(cancelToken);
LoadConditonRules(cancelToken);
LoadOperations(cancelToken);
}, cancelToken);
}
I pass the Token the Sub-Methods since the loops are actually there...