定时器不会再次启动

时间:2015-04-11 21:37:03

标签: vb.net function datagridview timer

我有一个功能:

Private Sub UpdateSch()
        Threading.Thread.Sleep(50)
        Dim i As Integer = 1
        While i = 1
            Try
                If DataGridView1.Rows.Count > 1 Then
                    DataGridView1.Rows.Clear()
                End If
                Using stream As System.IO.FileStream = System.IO.File.OpenRead("Z:\\SchData.txt")
                    Using reader As New System.IO.StreamReader(stream)

                        Dim line As String = reader.ReadLine()

                        While (line IsNot Nothing)
                            Dim columns = line.Split(";")
                            line = reader.ReadLine()
                            Dim index = Me.DataGridView1.Rows.Add()
                            Me.DataGridView1.Rows(index).SetValues(columns)
                        End While

                    End Using
                End Using
                Button88.Enabled = True
                DataGridView1.CurrentCell = DataGridView1.Rows(rowIndex).Cells(colIndex)
                i = 0
            Catch ex As Exception
                Threading.Thread.Sleep(50)
            End Try
        End While

        'Check for local updating
        If updatingSch = False Then
            DataGridView1.Enabled = False
            LockWarning1.Visible = True
            lockVar1 = 0
            LockTimer1.Start()
        Else
            updatingSch = False
        End If
    End Sub

然后我有一个计时器:

Private Sub LockTimer1_Tick(sender As Object, e As EventArgs) Handles LockTimer1.Tick
        LockWarning1.Visible = False
        DataGridView1.Enabled = True
        LockTimer1.Stop()
    End Sub

在表单加载和文件更改时调用函数updateSch。它锁定DataGridView,启动运行10秒的计时器,然后解锁Datagridview。这一切都在加载时起作用,但是当它再次被调用时它会锁定并且永远不会解锁。计时器第二次永远不会启动。 (我在“LockTimer1.Start()”上设置了一个断点,它是第二次执行,但LockTimer_Tick事件在此之后不会触发)

1 个答案:

答案 0 :(得分:2)

我找到了解决问题的方法。对于我的生活,我无法弄清楚为什么我以前的代码不起作用。我能够工作的是Systems.Timers.Timer(而不是System.Windows.Forms.Timer)。我创建计时器的代码如下所示:

Dim LockTimer1 As New System.Timers.Timer()
            LockTimer1.Interval = 10000
            LockTimer1.AutoReset = False 'Run timer only once
            LockTimer1.Start()
            AddHandler LockTimer1.Elapsed, AddressOf LockTimer1_Tick
然后是函数LockTimer1_tick:

 Private Sub LockTimer1_Tick(ByVal sender As Object, ByVal e As ElapsedEventArgs)
        LockWarning1.Visible = False
        DataGridView1.Enabled = True
        Button88.Enabled = True
        Button1.Enabled = True
    End Sub