Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
see my code
private async void button2_Click(object sender, EventArgs e)
{
List<Task<int>> tasks = new List<Task<int>>();
for (int i = 0; i < 5; i++)
{
tasks.Add(Getdata(i+1));
}
var result = await Task.WhenAll(tasks);
}
public async Task<int> Getdata(int i)
{
IProgress<string> progress = new Progress<string>(str =>
{
textBox1.Text = str;
});
await Task.Delay(90000);
progress.Report("Task completed "+i.ToString());
//return Task.FromResult(10);
return 10;
}
I storing multiple task into list and calling all the task in one go. I am writing text into textbox after delay completes but no text is getting printed in textbox....where i made the mistake.
This is a mocked up single Task but may help
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AsyncTaskProgress2
{
public partial class Form1 : Form
{
private CancellationTokenSource _cts = new CancellationTokenSource();
public Form1()
{
InitializeComponent();
}
private async void StartButton_Click(object sender, EventArgs e)
{
var cancelled = false;
if (_cts.IsCancellationRequested == true)
{
_cts.Dispose();
_cts = new CancellationTokenSource();
}
var progressIndicator = new Progress<int>(ReportProgress);
try
{
await AsyncMethod(progressIndicator, _cts.Token);
}
catch (OperationCanceledException)
{
StatusLabel.Text = "Cancelled";
cancelled = true;
}
if (!cancelled) return;
await Task.Delay(1000);
StatusLabel.Text = "Go again!";
}
private void CancelButton_Click(object sender, EventArgs e)
{
_cts.Cancel();
}
private static async Task AsyncMethod(IProgress<int> progress, CancellationToken ct)
{
for (int index = 100; index <= 120; index++)
{
//Simulate an async call that takes some time to complete
await Task.Delay(500, ct);
if (ct.IsCancellationRequested)
{
ct.ThrowIfCancellationRequested();
}
progress?.Report(index);
}
}
private void ReportProgress(int value)
{
StatusLabel.Text = value.ToString();
TextBox1.Text = value.ToString();
}
}
}