I've been trying to create a function call in a new Thread because if I use my main thread then my application get's too busy and can't be used anymore while the function is running.
Now I've been trying to create the function call inside a new Thread:
private void bunifuFlatButton2_Click(object sender, EventArgs e)
{
Thread thread = new Thread(new ThreadStart(worker));
thread.Start();
}
public void worker()
{
using (var streamReader = File.OpenText(filePath))
{
var lines = streamReader.ReadToEnd().Split(new char[] { '\n' });
var count = lines.Count();
bunifuProgressBar1.MaximumValue = count;
for (int i = 0; i < count; i++)
{
string[] words = lines[i].Split(':');
string hash = mega.GenerateHash(words[0].ToLowerInvariant(), mega.PrepareKey(words[1].ToBytes()));
bunifuCustomLabel4.Text = "Working: Total: " + count + ". Currently: " + (i + 1) + ".";
bunifuCustomLabel4.Update();
bunifuProgressBar1.Value = i + 1;
}
}
}
But now I receive the following error (Translated using google):
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll
Additional information: Invalid thread-spanning operation: Access to the bunifuCustomLabel4 control was from a thread other than the thread for which it was created.
How could I fix this error? I've been googling solutions but they didn't work also.
My latest attempt:
private void bunifuFlatButton2_Click(object sender, EventArgs e)
{
ThreadStart asyncCall = delegate
{
bunifuCustomLabel4.Invoke(new MethodInvoker(worker));
};
Thread thread = new Thread(new ThreadStart(worker));
thread.Start();
}