3

In the code below, I call method that opens a custom new window. However when application is doing some long running task I wish to still be able to activate the window. Is it possible to do it on another thread or by using the Task class?

public static class CustomW { static Custom_Window_Chrome_Demo.ThemedWindow MsgBox(string Msgbx_TTL, string Msgbx_Contnt) { var w_mbx = new Custom_Window_Chrome_Demo.ThemedWindow(); w_mbx.Width = 950; w_mbx.Height = 159; w_mbx.Title = Msgbx_TTL; Grid g = new Grid(); StackPanel spM = new StackPanel(); TextBlock TblckErrMsg = new TextBlock(); //more settings...... } } 

This is how I tried to invoke it,

public void newMsgBoxShow(string Msgbx_TTL, string Msgbx_Contnt) { System.Threading.Thread s = new System.Threading.Thread( ()=> CustomW.MsgBox(Msgbx_TTL, Msgbx_Contnt).Show() ); } 

but when I am using the new thread I am getting the following error.

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

What is the correct way to achieve the required result ?

6
  • Where is the long-running task? Commented Feb 8, 2016 at 12:50
  • Well you should run your long task on another threads and main tread leave for UI and non-heavy stuff. Commented Feb 8, 2016 at 12:52
  • @NicoSchertler the long task is searching DB long code.. Commented Feb 8, 2016 at 12:55
  • As suggested you should do your long running task on another thread, perhaps with a background worker. See here for explanations: codeproject.com/Articles/841751/… Commented Feb 8, 2016 at 12:55
  • @NawedNabiZada then I try the same (calling CustomW.MsgBox() )from the new thread same results Commented Feb 8, 2016 at 13:10

2 Answers 2

2

Use this:

 Task.Factory.StartNew(new Action(() => { //your window code }), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()); 

When new thread is created with Current Synchronization context it will be able to update the UI.(when current thread is UI thread)

You can also use dispatcher to execute your code.

 System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(()=> { //your window code })); 
Sign up to request clarification or add additional context in comments.

Comments

1

Take a look at Dispatcher
https://msdn.microsoft.com/cs-cz/library/system.windows.threading.dispatcher%28v=vs.110%29.aspx

Dispatcher.CurrentDispatcher.Invoke(delegate { /* CODE */ }, DispatcherPriority.Normal); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.