任务不按我需要的顺序进行

时间:2016-06-29 22:13:58

标签: wpf vb.net

我对任务有一个小问题..下面是我正在做的一个简单示例的屏幕截图。我希望ThirdJob首先出现,然后是SecondJob,然后是FirstJob(或者我正在做的任何顺序)。

enter image description here

我单击下拉框,它将任务添加到listbox1 ...然后我按下按钮,它会根据列表(任务)执行这些任务。

我在ThirdJob上有一个1000 MS的延迟,所以当然,它是最后一次。无论需要多长时间,我如何按照我想要的顺序进行制作。

目前的代码我用来做这个..

Dim tasklist As New List(Of Task)

Private Async Sub Button_Click(sender As Object, e As RoutedEventArgs)

    For Each item In tasklist
        'item.RunSynchronously()
        item.Start()
    Next

    Await Task.WhenAll(tasklist.ToArray)

End Sub

Public Sub FirstJob()
    Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, DirectCast(Function() listbox2.Items.Add("FirstJob"), Action))
End Sub
Public Sub SecondJob()
    Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, DirectCast(Function() listbox2.Items.Add("SecondJob"), Action))
End Sub
Public Sub ThirdJob()
    Thread.Sleep(1000)
    Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, DirectCast(Function() listbox2.Items.Add("ThirdJob"), Action))
End Sub

Private Sub ComboBox_SelectionChanged(sender As Object, e As SelectionChangedEventArgs)

    listbox1.Items.Add(cb1.SelectedItem)
    If cb1.SelectedItem.ToString = "FirstJob" Then
        tasklist.Add(New Task(Sub() FirstJob()))
    ElseIf cb1.SelectedItem.ToString = "SecondJob" Then
        tasklist.Add(New Task(Sub() SecondJob()))
    ElseIf cb1.SelectedItem.ToString = "ThirdJob" Then
        tasklist.Add(New Task(Sub() ThirdJob()))
    End If

End Sub

Private Sub MainWindow_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded
    cb1.Items.Add("FirstJob")
    cb1.Items.Add("SecondJob")
    cb1.Items.Add("ThirdJob")
End Sub

我确定问题在于我是如何通过我的阵列进行for循环的。

如果我改变

For Each item In tasklist
   item.Start()
Next

Await Task.WhenAll(tasklist.ToArray)

For Each item In tasklist
   item.Start()
   item.wait
Next

它按顺序排列,但冻结了我不想要的UI。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

如何创建自定义方法并使用UIViewController方法在彼此之后启动任务?

    let gView = GradientView()
    self.view.addSubview(gView)
    gView.translatesAutoresizingMaskIntoConstraints = false
    let gvCX = NSLayoutConstraint(item: gView, attribute: .CenterX, relatedBy: .Equal, toItem: self.view, attribute: .CenterX, multiplier: 1.0, constant: 0.0)
    let gvCY = NSLayoutConstraint(item: gView, attribute: .CenterY, relatedBy: .Equal, toItem: self.view, attribute: .CenterY, multiplier: 1.0, constant: 0.0)
    let gcH = NSLayoutConstraint(item: gView, attribute: .Height, relatedBy: .Equal, toItem: self.view, attribute: .Height, multiplier: 1.0, constant: 0.0)
    let gcW = NSLayoutConstraint(item: gView, attribute: .Width, relatedBy: .Equal, toItem: self.view, attribute: .Width, multiplier: 1.0, constant: 0.0)
    NSLayoutConstraint.activateConstraints([gvCX, gvCY, gvH, vW])

这将在彼此之后运行指定的任务。第一个完成后,第二个将启动,依此类推。

使用示例:

Task.ContinueWith()