Skip to main content
 首页 » 编程设计

c#之阻止函数并等待事件 C#

2024年02月20日13mayingbao

我想阻止一个函数并等待一个事件然后继续,在我的例子中是当我点击一个按钮时我想要的伪代码:

  • 弹出消息框
  • 等待数据 GridView 中的事件点击
  • 弹出消息框2
  • 等待数据 GridView 中的事件点击
  • 弹出是/否消息框
  • 执行另一个函数

但实际代码不等待 autoevent.Set() 函数,因此当我想阻塞主函数时,线程调用的函数仍然被阻塞。

我尝试了 ManualResetEvent 和 AutoResetEvent,这是我用于 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(); 
        } 
    } 

提前致谢

请您参考如下方法:

I would like to block a function and wait for an event then continue

这基本上不是事件驱动 GUI 的工作方式。您不应该阻塞 UI 线程 - 它会阻止屏幕刷新、窗口被拖动、关闭等。

相反,您应该禁用所有您不希望在其他处理正在进行时可用的操作,并且当事件发生时,回调到 UI 线程(例如使用 Control.Invoke) 重新启用相关控件,并继续您的逻辑。

C# 5 将使用异步方法使这一切变得更容易,因为这样您就可以编写看起来同步的代码,这些代码“等待”操作完成而不会阻塞线程 - 但您仍然需要弄清楚要禁用/启用什么什么时候。