Why am I getting this error:Cross-thread operation not valid: Control lbFolders accessed from a thread other than the thread it was created on.?
prgAll.Maximum = lbFolders.SelectedItems.Count;
On that line you perform an assignment (set/add), which by default is not thread-safe.
On the second line it's just a get operation, where thread-safety merely doesn't matter.
EDIT: I don't mean access to the prgAll element.
Accessing the Count property changes the internal state of the ListBox inner collection, that is why it throws the exception.
Cross-thread operation not valid: Control 'label1' accessed from a thread other than the thread it was created on
Update your label in your progress handler instead of inside the worker thread.
// On worker thread so do our thing!
void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// Your background task goes here
for (int i = 0; i <= 100; i++)
{
// Report progress to 'UI' thread
backgroundWorker1.ReportProgress(i);
// Simulate long task
System.Threading.Thread.Sleep(100);
}
}
// Back on the 'UI' thread so we can update the progress bar - and our label :)
void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// The progress percentage is a property of e
progressBar1.Value = e.ProgressPercentage;
label1.Text = String.Format("Trade{0}",e.ProgressPercentage);
}
C# Cross-thread operation not valid
You should Invoke backgroundWorker1.ReportProgress(1);
, because only UI thread can directly access UI controls. Example of invoking:
private delegate void AddListBoxItemDelegate(object item);
private void AddListBoxItem(object item)
{
if (this.listBox1.InvokeRequired)
{
// This is a worker thread so delegate the task.
this.listBox1.Invoke(new AddListBoxItemDelegate(this.AddListBoxItem), item);
}
else
{
// This is the UI thread so perform the task.
this.listBox1.Items.Add(item);
}
}
Cross-threading operation not valid
try below code
public void eng_OnGetSpeedDone(OBDIIEngineEventArgs args)
{
if (this.InvokeRequired)
{
Action action = () => eng_OnGetSpeedDone(args);
Invoke(action);
return;
}
if (!args.OBDResultNoData)
brzina_ele.Text = arg.OBDValue.ToString();
else
brzina_ele.Text = "0";
}
Solve a cross-threading Exception in WinForms
When making method calls to a control, if the caller is on a different thread than the one the control was created on, you need to call using Control.Invoke. Here is a code sample:
// you can define a delegate with the signature you want
public delegate void UpdateControlsDelegate();
public void SomeMethod()
{
//this method is executed by the background worker
InvokeUpdateControls();
}
public void InvokeUpdateControls()
{
if (this.InvokeRequired)
{
this.Invoke(new UpdateControlsDelegate(UpdateControls));
}
else
{
UpdateControls();
}
}
private void UpdateControls()
{
// update your controls here
}
Hope it helps.
Help needed for 'cross-thread operation error' in C#
Make always sure you update your GUI on the main thread (GUI thread).
foo.MessageReceived += new Agent.MessageReceivedHandler(foo_MessageReceived);
public delegate void MyDelegate(Message msg);
void foo_MessageReceived(Message message)
{
if (InvokeRequired)
{
BeginInvoke(new MyDelegate(foo_MessageReceived),new object[]{message});
}
else
{
label1.Text = message.Body;
}
}
Solve a cross-threading Exception in WinForms
When making method calls to a control, if the caller is on a different thread than the one the control was created on, you need to call using Control.Invoke. Here is a code sample:
// you can define a delegate with the signature you want
public delegate void UpdateControlsDelegate();
public void SomeMethod()
{
//this method is executed by the background worker
InvokeUpdateControls();
}
public void InvokeUpdateControls()
{
if (this.InvokeRequired)
{
this.Invoke(new UpdateControlsDelegate(UpdateControls));
}
else
{
UpdateControls();
}
}
private void UpdateControls()
{
// update your controls here
}
Hope it helps.
Unintentional multithreading in form application
You are using System.Timer. https://msdn.microsoft.com/en-us/library/system.timers.timer(v=vs.110).aspx
For winforms apps you are better off using the one for winforms...
https://msdn.microsoft.com/en-us/library/system.windows.forms.timer(v=vs.110).aspx
It is designed to support single threaded UIs. :-
A Timer is used to raise an event at user-defined intervals. This Windows timer is designed for a single-threaded environment where UI threads are used to perform processing. It requires that the user code have a UI message pump available and always operate from the same thread, or marshal the call onto another thread.
Related Topics
How to Expand a String That Contains C# Literal Expressions at Runtime
Mvvm Show New Window from Vm When Seperated Projects
Blocking Access to Private Member Variables? Force Use of Public Properties
Check for Null in Foreach Loop
Windows 7 Progress Bar in Taskbar in C#
Forms' Does Not Exist in the Namespace System.Windows
How to Deploy a .Net Application That Uses Odac Without Installing the Whole Component to the User
What's the Best Way to Test SQL Server Connection Programmatically
Database.Begintransaction VS Transactions.Transactionscope
Why Is a Round-Trip Conversion via a String Not Safe for a Double
Filter a List by Another List C#
Use Different Name for Serializing and Deserializing with JSON.Net
Find Image Format Using Bitmap Object in C#
How to Debug into My Nuget Package Deployed from Teamcity
Find Image Format Using Bitmap Object in C#