计时器勾选不起作用

时间:2014-05-12 18:04:18

标签: c# console-application

我的计时器有问题,它没有到达tick,我也没有看到问题。

class Class1
{
    bool check;
    Timer net;
    private bool timerComplete = false;
    private int timerIndex = 0;

    public Class1()
    {
        check = true;
        net = new Timer();
    }
    public void Do()
    {
        System.Threading.Thread.Sleep(4*1*1000);
        net.Interval = 1 * 1000;
        net.Tick+=new EventHandler(net_Tick);
        net.Start();
        while (!timerComplete)
            System.Threading.Thread.Sleep(1000);

    }

    void net_Tick(object sender, EventArgs e)
    {
        timerIndex++;
        if (timerIndex >= 10)
        {
            timerComplete = true;
            return;
        }
       //my code
    }
}

主要

这是我调用Do()函数

的地方
class Program
{
    const int SW_HIDE = 0;

    static void Main(string[] args)
    {
        Hide();
        Class1 c = new Class1();
        c.Do();
    }

    public static void Hide()
    {
        var handle = GetConsoleWindow();
        // Hide
        ShowWindow(handle, SW_HIDE);
    }

    [DllImport("kernel32.dll")]
    static extern IntPtr GetConsoleWindow();

    [DllImport("user32.dll")]
    static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
}

2 个答案:

答案 0 :(得分:2)

您忘记拨打Do(),这是设置计时器属性并启动它的方法。

编辑:

如果它是你的第二个计时器,那个没有工作的计时器(你仍然没有指定哪个计时器不工作),那是因为你正在创建它而不是保存任何对它的引用,因此你失去对它的控制。

答案 1 :(得分:0)

您的代码有点令人困惑,但基本上您正在寻找以下

static void Main(string[] args) {
    var myObject = new Class1();
    myObject.Do();

    // give the program 10 minutes to run. This is arbitrary so you will want to change
    //     to something realistic or have a callback to signal "done".
    System.Threading.Thread.Sleep(10 * 60 * 1000);
}

应该这样做,或者至少让你开始吧!

其他注意事项 - 另一个注意事项是第二个计时器调用名为net_Tick的方法。我在提供的代码中没有看到这一点,所以我认为没有问题...

替代方法

另一种方法是阻止Do方法而不是使主线程暂停,直到计时器完成(或者你想要停止)。为此,我添加了以下Class1中需要更改的代码片段:

public class Class1 {

    // add a variable for timer complete
    private bool timerComplete = false;
    private int timerIndex = 0;


    public void Do()
    {
        t.Enabled = true;

        // start timer same as normal:
        t.Interval = 10 * 1000;
        t.Tick += new EventHandler(t_Tick);
        t.Start();

        // busy wait to block the thread
        while (!timerComplete) {
           System.Threading.Thread.Sleep(1000);
        }
    }

    void t_Tick(object sender, EventArgs e)
    {
        // give this a stopping point
        timerIndex++;
        if (timerIndex >= 10) {
            timerComplete = true;
            return;
        }

        // leave the rest of the tick as it was before...
    }
}

执行此操作后,您可以从Sleep例程中删除对Main的调用,但一切都应该仍然有效。祝你好运!

相关问题