Assigning a property across threads
Posted
by Mike
on Stack Overflow
See other posts from Stack Overflow
or by Mike
Published on 2010-04-13T12:53:20Z
Indexed on
2010/04/13
13:03 UTC
Read the original article
Hit count: 427
c#
|multithreading
I have set a property across threads before and I found this post http://stackoverflow.com/questions/142003/cross-thread-operation-not-valid-control-accessed-from-a-thread-other-than-the-t about getting a property.
I think my issue with the code below is setting the variable to the collection is an object therefore on the heap and therefore is just creating a pointer to the same object
So my question is besides creating a deep copy, or copying the collection into a different List object is there a better way to do the following to aviod the error during the for loop.
Cross-thread operation not valid: Control 'lstProcessFiles' accessed
from a thread other than the thread it was created on.
Code:
private void btnRunProcess_Click(object sender, EventArgs e)
{
richTextBox1.Clear();
BackgroundWorker bg = new BackgroundWorker();
bg.DoWork += new DoWorkEventHandler(bg_DoWork);
bg.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bg_RunWorkerCompleted);
bg.RunWorkerAsync(lstProcessFiles.SelectedItems);
}
void bg_DoWork(object sender, DoWorkEventArgs e)
{
WorkflowEngine engine = new WorkflowEngine();
ListBox.SelectedObjectCollection selectedCollection=null;
if (lstProcessFiles.InvokeRequired)
{
// Try #1
selectedCollection = (ListBox.SelectedObjectCollection)
this.Invoke(new GetSelectedItemsDelegate(GetSelectedItems),
new object[] { lstProcessFiles });
// Try #2
//lstProcessFiles.Invoke(
// new MethodInvoker(delegate {
// selectedCollection = lstProcessFiles.SelectedItems; }));
}
else
{
selectedCollection = lstProcessFiles.SelectedItems;
}
// *********Same Error on this line********************
// Cross-thread operation not valid: Control 'lstProcessFiles' accessed
// from a thread other than the thread it was created on.
foreach (string l in selectedCollection)
{
if (engine.LoadProcessDocument(String.Format(@"C:\TestDirectory\{0}", l)))
{
try
{
engine.Run();
WriteStep(String.Format("Ran {0} Succussfully", l));
}
catch
{
WriteStep(String.Format("{0} Failed", l));
}
engine.PrintProcess();
WriteStep(String.Format("Rrinted {0} to debug", l));
}
}
}
private delegate void WriteDelegate(string p);
private delegate ListBox.SelectedObjectCollection GetSelectedItemsDelegate(ListBox list);
private ListBox.SelectedObjectCollection GetSelectedItems(ListBox list)
{
return list.SelectedItems;
}
© Stack Overflow or respective owner