Reputation: 1302
i would like to block a function and wait for an event then continue , in my case the pseudo-code that i want to have when i click a button:
but the actual code do not wait for autoevent.Set() function so the functions called by the threads remains blocked while i want to block the main function.
i tried ManualResetEvent and AutoResetEvent, this is the code that i used for AutoResetEvent :
public partial class person : Form
{
AutoResetEvent auto = new AutoResetEvent(false);
private void button1_Click(object sender, EventArgs e)
{
int old_id, new_id;
//dataGridView1.ClearSelection();
Thread t1 = new Thread(new ThreadStart(th_remove));
Thread t2 = new Thread(new ThreadStart(th_replace));
t1.Start();
old_id = (int)dataGridView1.SelectedRows[0].Cells[1].Value;
t2.Start();
new_id = (int)dataGridView1.SelectedRows[0].Cells[1].Value;
DialogResult dialogResult = MessageBox.Show("Remplacer", "Vous êtes sûr de vouloir remplacer ?", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
db.replace("person", new_id, old_id);
}
}
private void th_replace()
{
auto.WaitOne();
MessageBox.Show("Seléctionnez la ligne remplaçante");
}
private void th_remove()
{
auto.WaitOne();
MessageBox.Show("Seléctionnez la ligne à supprimer");
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
auto.Set();
}
}
Thanks in advance
Upvotes: 1
Views: 2624
Reputation: 1500515
I would like to block a function and wait for an event then continue
That's basically not how event-driven GUIs work. You shouldn't block the UI thread - it will stop the screen from refreshing, the window from being dragged, closed etc.
Instead, you should disable all actions that you don't want to be available while other processing is going on, and when the events occur, call back into the UI thread (e.g. using Control.Invoke
) re-enable the relevant controls, and continue with your logic.
C# 5 will make a lot of this easier with async methods, as then you can write synchronous-looking code which "awaits" operations completing without blocking the thread - but you'll still need to work out what to disable/enable when.
Upvotes: 3
Reputation: 666
You could try to add a synchronization object and use Monitor's methods Wait
and Pulse
on your sync object. That is you need to call Pulse
in your event handler and Wait
in your synchronous method. But make sure your event does not occur before you enter the Wait
state... =)
Good luck!
Upvotes: 1