从Task访问表单变量

时间:2017-10-13 17:41:58

标签: vb.net

当任务访问表单变量时是否有任何错误,或者是否存在与之相关的一些问题?

下面你可以看到一个例子。 _counter是表单的变量以及_subkategorie.Id and sentence.Id。当pic显示时 - 这是在长任务运行时向用户显示的另一种形式。当任务完成作业时,此附加表单将被关闭,因此ShowDialog将自动解锁主表单。这个任务是访问表单的变量,可以看出。

_counter = 0 'this is form's variable
  For _counter = 0 To LbSubkategories.Items.Count - 1
       If LbSubkategories.SelectedItems.Contains(LbSubkategories.Items(_counter)) Then     
            _subKategorieId = New Subkategorie().GetIdByName(LbSubkategories.GetItemText(LbSubkategories.Items(_counter)))

            pic = New FrmCircularProgress(eCircularProgressType.Donut)
            pic.ShowDialog()
            'Task.WaitAll(tsk_doesConnectionExist)  'not need as ShowDialog not return after pic is closed so further lines below will be not executed before it closed

    End If
Next

这是_pic表单出现时将触发的内容。请参阅我在那里使用_counter变量和之前提到的另外两个变量。

Public Sub DoTheJobWhenPicShown() Handles pic.Shown
    tskDoesConnectionExist = Task.Run(Of Boolean)(Function()
    Dim resu = False

    Try
        resu = New AmbessSentenceSubKategorie(_subKategorieId, _sentence.Id).CheckIfConnectionAlreadyExist()
       If resu = True Then
               LbSubkategories.Invoke(Sub()
                 LbSubkategories.SetSelected(_counter, False)
               End Sub)
        pic.Invoke(New Action(Sub() pic.LabelX1.Text = "Ende"))

            End If
            Catch ex As SqlException
            pic.Invoke(New Action(Sub() MessageBoxEx.Show(pic, ex.ToString(), Msg.T(eMsgCaption.Err), MessageBoxButtons.OK, MessageBoxIcon.Error)))
            Catch ex As Exception
            pic.Invoke(New Action(Sub() MessageBoxEx.Show(pic, ex.ToString(), Msg.T(eMsgCaption.Err), MessageBoxButtons.OK, MessageBoxIcon.Error)))
            Finally
             '--Close form once done (on GUI thread)
            pic.Invoke(New Action(Sub() pic.StopCircular()))
        pic.Invoke(New Action(Sub() pic.Close()))
        End Try

Return resu
End Function)
End Sub

0 个答案:

没有答案