標籤:
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
Visionpro學習筆記 :QuickBuild-Based Application Run-Once Button