簡體   English   中英

C# 中的 MessageBox、鎖和 System.Windows.Forms.Timer 問題

[英]MessageBox, lock and System.Windows.Forms.Timer problem in C#

我相信我對lock工作方式或System.Windows.Forms.Timer在 C# 中的工作方式有誤解。

所以我制作了一個簡單的 Windows 窗體應用程序 (.NET Framework),並從工具箱中向Form添加了一個Timer和一個Button Button在被點擊時啟動TimerTimer在一個虛擬對象上進入一個lock ,並在Tick事件上阻止它。 對於ButtonClick事件,我有以下方法:

private void button1_Click(object sender, EventArgs e)
{
    timer1.Enabled = true;
}

對於TimerTick事件,我有這個方法:

readonly object lockObj = new object();

private void timer1_Tick(object sender, EventArgs e)
{
    lock (lockObj)
    {
        MessageBox.Show("Entered the lock!");
        MessageBox.Show("Exiting the lock...");
    }
}

其他一切都保持默認,沒有額外的代碼。

我希望這個程序來顯示一個MessageBox與文本"Entered the lock!" ,然后在我關閉它以及以下帶有消息"Exiting the lock..."的消息后,我認為鎖將被釋放並且排隊的 Tick 事件(如果有的話)會獲取鎖,該過程會重復。 相反, "Entered the lock!" MessageBox會多次打開而不必關閉它,就好像每個Tick事件調用都會進入鎖,即使沒有人釋放它。

我試圖在控制台應用程序中復制它,但沒有運氣。 我很感激有關導致此問題的原因的提示,以便我知道在哪里查看它。

您可以在 Windows 窗體應用程序中測試的替代代碼:

using System;
using System.Drawing;
using System.Windows.Forms;

namespace Lock_Test_2
{
    public partial class Form1 : Form
    {
        Timer timer1;

        readonly object lockObj = new object();

        public Form1()
        {
            InitializeComponent();

            Button button1 = new Button();
            button1.Location = new Point(100, 100);
            button1.Size = new Size(187, 67);
            button1.Text = "button1";
            button1.Click += button1_Click;
            Controls.Add(button1);

            timer1 = new Timer();
            timer1.Tick += timer1_Tick;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            timer1.Enabled = true;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            lock (lockObj)
            {
                MessageBox.Show("Entered the lock!");
                MessageBox.Show("Exiting the lock...");
            }
        }
    }
}

System.Windows.Forms.Timer通過 Windows 消息循環調度其事件。

MessageBox.Show顯示一個消息框,然后將 Windows 消息循環作為嵌套循環進行泵送。 這可以包括為計時器調度更多事件。

由於只涉及一個線程(UI 線程),並且lock是可重入的,這就是為什么會顯示多個消息框的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM