在VB.NET中设置手动超时

时间:2015-04-08 13:34:40

标签: vb.net multithreading timeout

我有一个vb.net应用程序,它与一些外部硬件接口 - 一组电机控制器。为此,我使用的是硬件供应商提供的CANOpen库。但是,库中内置的超时显然过多,导致应用程序在特定条件下痛苦地挂起。如果可能,我宁愿不需要编辑库。

在vb.net中设计另一个更短暂的超时时间最明智的方法是什么?有问题的函数是一个阻塞函数,因此可能在线程计时器无济于事。这里有优雅的解决方案吗?

1 个答案:

答案 0 :(得分:0)

试一试,这是迄今为止我能想到的最好的。我之所以使用后台工作人员只是因为它们易于使用。

基本上它是一个线程中的一个线程,它至少会保持你的UI响应,根据你所说的你可能应该使用线程来驱动所有驱动器通信功能,以防驱动器失去通信应用程序运行时的任何原因。

这很不错,但至少可以让你在CAN功能自身超时之前提前退出。

Private connected As Boolean

Private Sub bwTryConnect_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bwTryConnect.DoWork
    Dim timeout As Boolean
    Dim timeoutCount As Integer
    Dim timeoutValue As Integer = 5 ' timeout value
    bwConnect.RunWorkerAsync() ' start worker to try connection
    While bwConnect.IsBusy And Not timeout
        Thread.Sleep(1000) ' wait a second
        timeoutCount += 1 ' increment timeout value
        If timeoutCount = timeoutValue Then timeout = True ' connection timed out
    End While
    ' connected will be true if the try connection worker completed (connection to drive ok) before the timeout flag was set, otherwise false
    connected = Not timeout
End Sub

Private Sub bwConnect_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bwConnect.DoWork
    ' use your CAN library function here - either a simple connect command or just try reading an arbitary value from the drive
    ' if you want to test this, uncomment one of the following lines:
    'Thread.Sleep(20000) ' simulate timeout
    'Thread.Sleep(2000) ' simulate connect
End Sub

显然,您随后拨打bwTryConnect.RunWorkerAsync()