I got problem during using async Task in C#. When I try to close Form2 during execution Task "DoSomeThing", the Visiual Studio show the next mistake "System.Reflection.TargetInvocationException".How can it be fixed? Form 1 (has button to go to Form2)
public Form1()
{
InitializeComponent();
}
private void AddWindow_FormClosed(object sender, FormClosedEventArgs e)
{
this.Show();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 ukl = new Form2 ();
ukl.FormClosed += new FormClosedEventHandler(AddWindow_FormClosed);
ukl.Show();
this.Hide();
}
Form2
static CancellationTokenSource cts;
public Form2()
{
InitializeComponent();
}
private async void Form2_Load(object sender, EventArgs e)
{
cts = new CancellationTokenSource();
await DoSomeThing(cts.Token);
}
async Task DoSomeThing(CancellationToken token)
{
while(double.Parse(label1.Text )< 100)
{
if (token.IsCancellationRequested)
{
return;
}
label1.Text = (double.Parse(label1.Text) + 1).ToString();
await Task.Delay(100);
}
}
private async void Form2_FormClosed(object sender, FormClosedEventArgs e)
{
cts = new CancellationTokenSource();
cts.Cancel();
await DoSomeThing(cts.Token);
}
I tried to use Cancellation Token, but it did't help