Reputation: 43
I am using a BackGroundWorker
to access some data and read it. But I need to open up a new wpf window inside the code that reads the data. (synchronous)
When I am doing this I am getting an error.
I tried adding [STAThread]
above the functions that opens a new window but this doesn't work.
Method that opens the new window:
[STAThread]
int returnColumnStartSelection(string filePath)
{
ColumnStartSelection css = new ColumnStartSelection(filePath);
css.ShowDialog();
return css.lineStart;
}
Entry point for the new Window:
public ColumnStartSelection(string filePath)
{
InitializeComponent();
//
this.Topmost = true;
this.WindowStartupLocation = WindowStartupLocation.CenterScreen;
}
Upvotes: 1
Views: 1120
Reputation: 43
My solution:
I stoped using the BackgroundWorker
and started using aysnc
and await
.
For my STAThread
problem I build a new Method that creates a new STAThread and the other Thread just waits until a Value change.
string selectTable(myDataTable dt)
{
string column = null;
Thread thread = new Thread(() =>
{
TableSelection ts = new TableSelection(dt);
ts.ShowDialog();
column = ts.column;
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
while (column == null)
{
Thread.Sleep(50);
}
try { thread.Abort(); } catch { }
return column;
}
Upvotes: 2
Reputation: 71
Hopefully I understand your question. If not, feel free to correct me.
To open a new window from within the BackgroundWorker_DoWork method, you can use the Dispatcher as mentioned in the comments:
Application.Current.Dispatcher.Invoke((Action)delegate
{
EmailEnter emailer = new EmailEnter("Transfer", employee);
emailer.ShowDialog();
});
That is an example from some of my working code. The employee variable is local to the background worker method and is sent to the EmailEnter constructor as a parameter. The window is then opened using .ShowDialog().
I called this at the end of my BackgroundWorker_DoWork method.
In your case, you would want to replace EmailEnter with ColumnStartSelection and pass your filePath variable to it.
Please let me know if you want me to clarify anything.
Upvotes: 0