Share via


calling a WPF from my thread with dispatcher still fails? why?? An object reference is required for the non-static field...?

Question

Tuesday, October 12, 2010 8:53 AM

this is my code. I got a compilation error on my test() method, which is to display a WPF form:

Error 1 An object reference is required for the non-static field, method, or property 'System.Windows.Threading.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority, System.Delegate, object)' ...

please help. thanks

Jessi

private void bw_DoWork(object sender, DoWorkEventArgs e) 

{
   test();
}

private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) 
{
 ...
}
 

private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e) 

{
  ...
} 

public void main() 

{
  ShowExceptionDialog = new ExceptionDelegate(ShowException);
  
  bw.WorkerReportsProgress = true;

  bw.WorkerSupportsCancellation = true;

  bw.DoWork += new DoWorkEventHandler(bw_DoWork); 

  bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged); 

  bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted); 


  if (!bw.IsBusy)

   bw.RunWorkerAsync();

 ...

 ...

}

public void test()

{ 
  eInfo = new ExceptionInfo(); 

   Dispatcher.Invoke(DispatcherPriority.Normal, 

     new Action<ExceptionInfo>(ShowExceptionDialog), eInfo);

}

All replies (6)

Tuesday, October 12, 2010 10:34 AM âś…Answered

Hi,

In order to have it run asynchronously, you should use the BeginInvoke Method on the Dispatcher, so use Dispatcher.CurrentDispatcher.BeginInvoke. This will ensure the method will be invoked on the UI thread.

Hope this helps
Meile Zetstra


Tuesday, October 12, 2010 9:32 AM

Hi,

You should actually call the Dispatcher.CurrentDispatcher.Invoke.

Hope this helps
Meile Zetstra


Tuesday, October 12, 2010 9:41 AM

Hi,

You should actually call the Dispatcher.CurrentDispatcher.Invoke.

Hope this helps
Meile Zetstra

Thanks Meile, it can compile now. But I got runtime error this time.

My code

Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Normal, 
          new Action<ExceptionInfo>(ShowExceptionDialog), eInfo);

runtime error:

The calling thread must be STA, because many UI components require this

 

please help. thanks

jessi

1 + 1 = 3


Tuesday, October 12, 2010 10:08 AM

Add an STAThread attribute to your Main.


Tuesday, October 12, 2010 10:10 AM

How? pls let me know. I am just an art student. just learned c# 3 months ago1 + 1 = 3


Tuesday, October 12, 2010 10:16 AM

i have put the

[

STAThread], the result is still the same. calling thread must be STA....

on my main method

[STAThread]

public void main()

1 + 1 = 3