質問
私はこのようなものを実装しようとしています:
For Each person In db.Persons.Where(Function(x) x.Name = requestedName)
If AbortRequested Then Exit For
MyFunc(person)
Next
Exit For がループをすばやく終了することを期待していましたが、間違っていました。通常のクエリに 60 秒かかる場合、中止されたクエリにも同じ時間が必要です: 60 秒。中止されたクエリと中止されていないクエリの唯一の違いは、「MyFunc(person)」が残りの人に対して実行されないことです。
しかし、ループ時間を短縮するには中断する必要があります。私は何をすべきか?
解決
ピアのアドバイスに基づいて、次のコードを実装しましたが、正常に動作します。
Dim tokenSource As New CancellationTokenSource()
Dim taskGetTests = Task.Factory.StartNew(Sub()
For Each person In db.Persons.Where(Function(x) x.Name = requestedName)
If AbortRequested Then
tokenSource.Cancel()
Exit For
End If
MyFunc(person)
Next
End Sub , tokenSource.Token)
taskGetTests.Wait(tokenSource.Token)