P
P
Pavel Kaptur2016-01-25 13:53:11
WPF
Pavel Kaptur, 2016-01-25 13:53:11

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"

How can I make it so that I can work with this object in a thread? I want to process the elements of the list and then remove them from the list and from the ListBox in which they are presented on the form.
I just recently started learning C#, so all sorts of LINQ and other expressions scare me, and I ask you to explain as simply as possible and using the most classic syntax.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Peter, 2016-01-25
@petermzg

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 question

Ask a Question

731 491 924 answers to any question