Answer the question
In order to leave comments, you need to log in
What is the correct way to pass an object to a thread and change it in the thread?
Hello, I am writing a small program, the essence of which is to create a list of certain commands, batch processing this list. Those. just follow the commands in sequence. For this I use a list of objects List<GeneralCommand> Commands;
. This list is defined in the window's constructor. I wanted to move the processing of commands to a separate thread, and execute them in it and change the value of the progress bar, etc. To do this, I need to pass this list to the thread, for which I use ParameterizedThreadStart, but still, when I try to cast the type to an element of this list, I get an error
InvalidOperationExeption was unhandled and the explanation "The calling thread cannot access this object because another thread owns this object"
Answer the question
In order to leave comments, you need to log in
Directly changing visual elements from a thread in which they were not created will not work (updating the progress bar). You will have to do synchronization via invoke or synchronization context.
And the data is well transferred:
private void button1_Click(object sender, EventArgs e)
{
List<string> lstTest = new List<string>();
var thread = new Thread(Start);
thread.Start(lstTest);
}
private void Start(object obj)
{
List<string> lstTest = (List<string>)obj;
int count = lstTest.Count();
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question