I want to report numbers out of a task to the UI. That doesn’t work directly, see code below (exception message appears). How does it work with progress. Report ?

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace _1510_Zahl_in_Label_auf_UI_ausgeben_mit_Task_und_Fehler
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void CmdStart_Click(object sender, EventArgs e)
{
Task task = new Task(Zaehlmethode);
task.Start();
}
void Zaehlmethode()
{
for (int i = 0; i <= 100; i++)
{
LblAusgabe.Text = i.ToString();
LblAusgabe.Refresh();
Thread.Sleep(50);
}
}
private void CmdEnde_Click(object sender, EventArgs e)
{
this.Close();
}
}
}

Yeah, trying to modify UI elements from another thread will throw exceptions.
Create a method called UpdateLabel(int i) that updates the label with ‘i’.
Then pass an IProgress<int> as a parameter to Zaehlmethode like this: Zaehlmethode(new Progress<int>(i => UpdateLabel(i));
Then in the loop you can do: progress.Report(i);

I realize your title is asking to not use lambdas, but why?
Yes, thank you, it works, but I want to seperate all parameters, handlers etc. that’s why I would like to use named methods without lambda expressions. It’s a better way to show it to my pupils, because they don’t know about lambdas.
Thank you!
C# devs
null reference exceptions

source