I have a method for exporting data. I do it via a new thread so that the GUI remains responsive. At the end it opens a SaveFileDialog which is not working without an invoke. With the below modification it's working but again, the GUI is unresponsive. Any clue?
private void button1_Click(object sender, EventArgs e)
{
Thread thread = new Thread(method);
thread.Start();
}
public void medhod()
{
if (this.InvokeRequired)
{
Invoke(new MethodInvoker(delegate() { method(); }));
}
else
{
//Code
//SaveFileDialog
}
}
*Edit: Another approach would be to leave the export code in the new thread, and put the SaveFileDialog back to the original thread. All I need is 1st thread to "pause" and then continue once the 2nd thread is over. Ideas are welcome.
Your issue is probably what Luaan comment points. You have long operation which you want to put into thread, but then you invoke the whole operation into UI thread and it will block the UI thread for a duration.
Do it like this:
private void button1_Click(object sender, EventArgs e)
{
(new Thread(method)).Start();
}
private void method()
{
//Code
Invoke(() =>
{
//SaveFileDialog
});
}
You don't need to check for InvokeRequired, because it will be required anyway. The way you use it is a pattern of defining method, which can be called from either thread. But in this case it typically contains very short operation to interact with UI controls.
The problem is running any sort of UI component in a non-UI thread is generally a bad idea - especially a modal dialog.
Instead, put the actual background processing code into another thread and once finished call back into the UI thread and launch the save dialog. The TPL makes this sort of thing very trivial e.g.
Task.Factory.StartNew(() => {
// do background processing
}).ContinueWith((task) => {
// show save dialog
}, TaskScheduler.FromCurrentSynchronizationContext());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With