L
L
libera2016-03-07 19:05:22
WPF
libera, 2016-03-07 19:05:22

Calling an object from another thread?

private void button2_Click(object sender, RoutedEventArgs e)
        {
            Thread myThread = new Thread(new ThreadStart(Count));
            myThread.Start(); // запускаем поток
            for (int i = 1; i < 200; i++)
            {
                
                label9.Content=(i * i);
                Thread.Sleep(300);
            }
        }
        public void Count()
        {
            for (int i = 1; i < 200; i++)
            {
                label9.Content=(i * i); // ошибка тут
                Thread.Sleep(400);
            }
        }

Error, The called thread cannot access objects from another thread.
How to solve this problem?
And what if I have to access 5-10 objects in another thread.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
ar4ebaldello, 2016-03-07
@ar4ebaldello

public void Count()
{
    for (int i = 1; i < 200; i++)
    {
        int local = i * i;
        Dispatcher.Invoke(()=>label9.Content = local);
        Thread.Sleep(400);
    }
}

A
Anton Fedoryan, 2016-03-09
@AnnTHony

And what if I have to access 5-10 objects in another thread.

Read about working with streams ?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question