1) Creating a Run-Once Button
通過JobManager調用VisionPro文件。所有的過程放到一個Try/Catch塊中。
Private Sub RunOnceButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RunOnceButton.Click Try myJobManager.Run() Catch ex As Exception MessageBox.Show(ex.Message) End Try End Sub 多次點擊Button會發現有錯誤:CogNotStopperException。原因是我們是異步調用VisionPro的,要等到程序結束之后才可以繼續調用。
2) Handling Job Manager Events
防止用戶在程序未完時再次調用:
Private Sub RunOnceButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RunOnceButton.Click Try RunOnceButton.Enabled = False myJobManager.Run() Catch ex As Exception MessageBox.Show(ex.Message) End Try End Sub 同時需要在Job完成時通知用戶Button可以再次使用了。於是添加JobManager的Stopped事件:
Private Sub myJobManager_Stopped(ByVal sender As Object, ByVal e As CogJobManagerActionEventArgs) RunOnceButton.Enabled = True End Sub
接下來如何讓Job manager知道有這么一個事件在等他:利用Addhandler來注冊事件的句柄:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
myJobManager = CType(CogSerializer.LoadObjectFromFile("C:\Program Files\Cognex\VisionPro\Samples\Programming\QuickBuild\advancedAppOne.vpp"), CogJobManager) myJob = myJobManager.Job(0) myIndependentJob = myJob.OwnedIndependent
myJobManager.UserQueueFlush() myJobManager.FailureQueueFlush() myJob.ImageQueueFlush() myIndependentJob.RealTimeQueueFlush()
AddHandler myJobManager.Stopped, AddressOf myJobManager_Stopped End Sub 當注冊事件的句柄時,在程序關閉時需要移除句柄:
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing RemoveHandler myJobManager.Stopped, AddressOf myJobManager_Stopped myJobManager.Shutdown() End Sub 當我們運行以上程序時還會有錯誤:Cross-thread operation not valid。
3)Handling Cross-Thread Function Calls
Remember that the job manager creates several threads. One of these threads fires the Stoppedevent that runs the stopped event handler and eventually attempts to reenable the Run Oncebutton. This sequence of events is illegal because a button -- or any other Microsoft Windows Forms control -- can only be accessed by the thread that created that control. The button was not created by any of the job manager threads.
原因是Job manager在運行時同時創建了幾個線程。當其中某一個線程完成時也會觸發Stopped事件,這時顯示的“Run Once”按鈕可用是虛假的。如何保證在真正完成時觸發,可考慮用Delegate,委托是類型安全的。
在Stopped事件句柄之前添加:
Delegate Sub myJobManagerDelegate(Byval sender As Object, ByVal e As CogJobManagerActionEventArgs)
檢查句柄是否為錯誤的線程調用,如果是的話就利用委托創建句柄的指針,再用Invoke循環調用:
Private Sub myJobManager_Stopped(ByVal sender As Object, ByVal e As CogJobManagerActionEventArgs) If InvokeRequired Then Dim myDel As New myJobManagerDelegate(AddressOf myJobManager_Stopped) Dim eventArgs() As Object = {sender, e}
Invoke(myDel, eventArgs) Return End If RunOnceButton.Enabled = True End Sub