When executing this code

Paragraph par =new Paragraph(); par.Inlines.Add(msgToSend.strMessage); ChatBox.Document.Blocks.Add(par); 

An exception is thrown "how can you solve this problem?"

  • look at that . The key word is invoke . - KoVadim
  • I tried instead of ChatBox.Document.Blocks.Add (par); write this.Dispatcher.Invoke ((Action) (() => {ChatBox.Document.Blocks.Add (par);})); The result is the same. Can code sample be exactly in my case? - Stope
  • And what is the exception when trying to use Dispatcher? The same? - Maxim Kamalov 5:46 pm
  • Yes, the same. - Stope
  • The AsyncCallback delegate is used which creates a new thread if this helps. - Stope

1 answer 1

Perhaps not the best way, but in my case it works. Used form.invoke. The progress bar was made, which was updated in the window, depending on the calculations in another thread. So, the code in the main window of type ImageConverterForm: Form with progress bar

 public void ProgressHandler(int p) { if (progressBar.Value < progressBar.Maximum) { progressBar.Value += p; } } 

Call code for changing property value

 MainForm.Invoke(new ThreadStart(delegate { MainForm.ProgressHandler(1); })); 

Update: for the WPF application, nothing has changed except for invoking. New form

 MainForm.Dispatcher.Invoke(new ThreadStart(delegate { MainForm.ProgressHandler(1); })); 

where MainForm is a form of InvokeMainWindow: Window

  • I am using WPF and not Windows Forms. - Stope
  • repeated the same for WPF, nothing has changed, except for the MainForm.Invoke line (became main.Dispatcher.Invoke ( - Carma
  • Thanks, everything works) - Stope
  • Maybe BeginInvoke better in your case. And new ThreadStart is superfluous. - VladD
  • 2
    @Carma: I did not quite put it right, sorry. ThreadStart has certain semantics - this is the delegate used to start a new thread. I usually write this: Dispatcher.BeginInvoke ((Action) (() => MainForm.ProgressHandler (1))); that is, I use a more neutral Action . - VladD