使用AutoResetEvent

时间:2014-02-20 17:41:50

标签: c# .net multithreading

我尝试使用AutoResetEvent暂停执行click事件,直到传入的事件被触发但它不起作用它只在我不再需要它之后才能工作。

以下是它的示例代码

using System;
using System.IO;
using System.Threading;
using System.Windows.Forms;
namespace ATModem
{
    public partial class frmMain : Form
    {
        public AutoResetEvent receiveNow = new AutoResetEvent(false);

        Queue<string> q = new Queue<string>();

        public frmMain()
        {
            InitializeComponent();
            objclsSMS.incoming += objclsSMS_incoming;
        }

        void objclsSMS_incoming(string response)
        {
            log_events("Incoming Event: " + response);
            q.Enqueue(response);
            receiveNow.Set();
        }

        private void test_Click(object sender, EventArgs e)
        {
            receiveNow.Reset();
            test.Enabled = false;
            test.Text = "Waiting...";

            if (receiveNow.WaitOne(5000)){
                while (q.Count != 0)
                {
                    try
                    {
                        MessageBox.Show(q.Dequeue());
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error: \n" + ex.Message);
                    }
                }
            }else{
                MessageBox.Show("Request Timed out");
            }
        }
    }
}

0 个答案:

没有答案