0

I'm beginner in c#,and i write this code for start the new thread:

Thread workerThread = new Thread(DoWork);
workerThread.Priority = ThreadPriority.Highest;
workerThread.Start();


in the up thread process some thing and show into the chart,every thing is okay,but when run and finish DoWork method,chart control visible set to false automatically!,my DoWork method is:

public void DoWork()
{
     //.....some process and show into the process result into the chart
     chart1.Visible = true;//this code not run
}


how can solve that?

Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
behzad razzaqi
  • 1,503
  • 2
  • 18
  • 33

2 Answers2

4

You do not have access to UI elements from a different thread.

For Winforms: How to update the GUI from another thread in C#?

For WPF: Change WPF controls from a non-main thread using Dispatcher.Invoke

chart1.Dispatcher.Invoke(() =>chart1.Visible = true);
Community
  • 1
  • 1
Slime recipe
  • 2,223
  • 3
  • 32
  • 49
  • If he **were** trying to access UI element from another thread, he should have got an exception thrown. I don't think he mentioned that... – shay__ Jul 22 '15 at 07:53
  • 1
    Indeed, but for all you know he could've got an exception which was handled silently. – Slime recipe Jul 22 '15 at 08:50
0

Change your Dowork method signature to accept object as parameter and pass Synchronization context to it:

    void DoWork(object o)
    {           
        SynchronizationContext cont = o as SynchronizationContext;

        // your logic gere
        cont.Post(delegate
        {
            // all your UI updates here 
        }, null);
    }

   Thread workerThread = new Thread(DoWork);
   workerThread.Priority = ThreadPriority.Highest;
   workerThread.Start(SynchronizationContext.Current);
Fabjan
  • 13,506
  • 4
  • 25
  • 52