赢取表格应用冻结发布时

时间:2014-04-10 23:30:53

标签: c# winforms events textbox

让我首先承认我是一个相当绿色的程序员,但我陷入困境,试图弄清楚我的应用程序有什么问题。

到目前为止,目标是在单击按钮时启动计时器,并在文本框中连续显示已用时间。

可能有更好的方法来实现这一点但是让我幽默一下,我练习创建事件并在程序中使用它们。

当我启动代码时,我看到的是它只是冻结并且永远不会恢复,我需要使用任务管理器结束应用程序。

关于我可能做错了什么以及如何修复它的任何指示都将不胜感激。

// see clock class below containing delegate and event instantiation

public class Clock
{
    public delegate void TimeChangedHandler(object clock, TimeEventArgs timeInfo);
    public TimeChangedHandler TimeChanged;

    public void RunClock()
    {
        TimeEventArgs e = new TimeEventArgs();//initialize args
        while (e.keepCounting)
        {
            Thread.Sleep(1000);
            e.EndTime = DateTime.Now;

            if (e.StartTime != e.EndTime)
            {
                e.duration = e.EndTime.Subtract(e.StartTime);
            }

            if (TimeChanged != null)
            {
                TimeChanged(this, e);
            }


        }
    }


//see timeevent args description below:

public class TimeEventArgs : EventArgs
{
    public TimeSpan duration;
    public DateTime StartTime { get; set; }
    public DateTime EndTime { get; set; }
    public bool keepCounting = false;

    public TimeEventArgs()
    {
        StartTime = DateTime.Now;
        EndTime = DateTime.Now;
        keepCounting = true;
    }
}


//See form class below:

  public partial class TimeApp : Form
{


    public TimeApp()
    {
        InitializeComponent();

    }

    private void startStopButton_Click(object sender, EventArgs e)
    {
        var theClock = new Clock();
        var timeApp = new TimeApp();
        timeApp.Subscribe(theClock);
        theClock.RunClock();

    }

    public void Subscribe(Clock theClock)
    {
        theClock.TimeChanged += new Clock.TimeChangedHandler(NewTime);
    }

    public void NewTime(object theClock, TimeEventArgs e)
    {

        displayBox.Text = e.duration.Hours.ToString() + ":"
            + e.duration.Minutes.ToString() + ":" + e.duration.Seconds.ToString();
    }


}

2 个答案:

答案 0 :(得分:1)

您的RunClock方法会阻止用户界面(由于Thread.Sleep(1000);调用),这使得无法停止。

您应该考虑在表单中添加Windows.Forms.Timer而不是循环,而是使用它来驱动时钟。

答案 1 :(得分:0)

您在调用Thread.Sleep(1000)时暂停主(UI)主题 - 这就是您的应用无响应的原因。

使用Timer(而不是Thread.Sleep())并将任何处理/长时运行的代码分拆到BackgroundWorker,以便进行任何处理。这样,您的用户界面就会保持响应。