You can only update the GUI from the main thread.
In your worker method (calculate()) you are trying to add items to a listbox.
lbPrimes.Items.Add(currval.ToString());
This causes the exception.
You are accessing the control in a manner that is not thread safe. When a thread that did not create the control tries to call it, you'll get an InvalidOperationException.
If you want to add items to the listbox you need to use InvokeRequired as TheCodeKing mentioned.
For example:
private delegate void AddListItem(string item);
private void AddListBoxItem(string item)
{
if (this.lbPrimes.InvokeRequired)
{
AddListItem d = new AddListItem(item);
this.Invoke(d, new object[] { item});
}
else
{
this.lbPrimes.Items.Add(item);
}
}
Call this AddListBoxItem(...) method within your Calculate() method instead of directly trying to add items to the listbox control.