2

根据文章Lock Up Unlocked对死锁的 C# Windows 窗体应用程序实施更改后, 我仍然遇到与文章Locked Up 的先前代码相同的问题!

也就是说,在快速单击按钮几次后,应用程序会挂起(变得无响应)。

为什么?
以及如何纠正?

using System;
using System.Windows.Forms;
using System.Threading;

namespace LockupUnlocked
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
      _t = new Thread(new ParameterizedThreadStart(WorkerThread));
    }

    private Thread _t;
    private object lockObject = new object();

    private bool StopThread = false;  ////changes added to avoid deadlock

    private void WorkerThread(object sender)
    {
      Thread.Sleep(1000);
      //while (true)
      while (!StopThread)//changes added to avoid deadlock
      {
        string result = "This is a Test";
        IAsyncResult aResult;////changes added to avoid deadlock
        lock (lockObject)
        {
          Thread.Sleep(25);
          //lblResult.Invoke(new MethodInvoker(delegate { lblResult.Text = result; }));
          aResult = lblResult.BeginInvoke//changes to avoid deadlock
            (new MethodInvoker(delegate { lblResult.Text = result; }));
        }
        lblResult.EndInvoke(aResult);//changes added to avoid deadlock
        Thread.Sleep(500);
      }
    }
    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
      StopThread = true;
    }
    private void Form1_Load(object sender, EventArgs e)
    {
      _t.Start();
    }

    private void button1_Click(object sender, EventArgs e)
    {
      lock (lockObject)//changes added to avoid deadlock
      {
        lblResult.Text = "Override the Test";
      }
    }
  }
}
4

2 回答 2

3

对我来说,这看起来像是锁争用,不一定是死锁。

您每 25 毫秒(不是 25 秒,那将是 25000)迭代一次 while 循环,然后单击按钮会中断这个请求锁定,因为睡眠在锁定范围内,它可能永远不会被赋予该锁定。

如果不单击按钮,这可能看起来有效,但是,单击等待锁定的按钮将阻塞 UI 线程,导致出现“未响应”消息,因为表单没有可用的时间来绘制自己。

您实际上不需要锁定以更新文本值。当您从 a 调用时Control,它只是将消息推送到 UI 消息队列中,该队列在 UI 线程上同步处理。您可以做的最糟糕的事情是竞争条件,它不会破坏任何共享状态。

删除锁定,代码应该仍然可以按预期工作。


我不愿提供任何示例代码,因为我不知道您要使用此示例实现什么目标。

于 2013-02-26T10:13:52.150 回答
2

在 Windows.Forms 中使用需要 GUI 访问的冲突线程的模式涉及 InvokeRequired 属性和 Invoke 函数。那么就不需要加锁了。

namespace WindowsFormsApplication1
{
  using System;
  using System.Threading;
  using System.Windows.Forms;

  public partial class Form1 : Form
  {
    private Thread thread;

    public Form1()
    {
      this.InitializeComponent();
      this.thread = new Thread(this.WorkerThread);
    }

    private void WorkerThread(object sender)
    {
      Thread.Sleep(1000);

      while (true)
      {
        Thread.Sleep(25);

        this.SetText("from thread");

        Thread.Sleep(500);
      }
    }

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
      this.thread.Abort();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
      this.thread.Start();
    }

    /// <summary>
    /// This is a callback for the SetText Method.
    /// </summary>
    /// <param name="text">The text.</param>
    private delegate void SetTextCallback(string text);

    /// <summary>
    /// This sets a text. 
    /// It's thread safe, you can call this function from any thread. 
    /// If it's not called from the UI-thread, it will invoke itself
    /// on the UI thread.
    /// </summary>
    /// <param name="text">The text.</param>
    private void SetText(string text)
    {
      if (this.InvokeRequired)
      {
        this.Invoke(new SetTextCallback(this.SetText), text);
      }
      else
      {
        this.lblResult.Text = text;  
      }
    }

    private void Button1_Click(object sender, EventArgs e)
    {
      this.SetText("from button");
    }
  }
}
于 2013-02-26T10:34:50.887 回答