0

I have the following code

Dim x As Integer = 0
Dim evtReport(SomeMap.Keys.Count - 1) As ManualResetEvent
 For Each DeviceIp As String In SomeMap.Keys

    evtReport(x) = New ManualResetEvent(False)
    Dim thdReport As New Thread(New ParameterizedThreadStart(Sub() Me.CollectReportsNew(DeviceDetailsMap(DeviceIp), evtReport(x))))

    thdReport.Name = "Something"
    thdReport.Start()
     If (x < evtReport.Count - 1) Then
        x = x + 1
     End If
 Next

Now what I am trying to do is set the ManualReset event by index from inside the CollectReportsNew method.

But, inside the CollectReportsNew method, I see the same evtReport element sent. That is because the last index of x is sent instead of each thread getting its own element.

I don't understand why this is happening.

David
  • 2,298
  • 6
  • 22
  • 56
Som Bhattacharyya
  • 3,972
  • 35
  • 54
  • I can only see x being changed inside the if statement - i'd check to ensure the if statement is dropping into its code or not - I suspect it isnt. – FreudianSlip Feb 09 '17 at 07:42
  • This could be a case of [Acces to modified closure](https://weblogs.asp.net/fbouma/linq-beware-of-the-access-to-modified-closure-demon). Convert your lambda to an anonymous function/delegate with a temp variable of x. – Alex B. Feb 09 '17 at 07:44
  • @FreudianSlip Even without the if statement it looks like it takes the last value of x when passing on to the `CollectReportsNew ` method. – Som Bhattacharyya Feb 09 '17 at 07:49
  • @AlexB.is that supported in VB ? Can you point me to an example please. – Som Bhattacharyya Feb 09 '17 at 07:50
  • Possible duplicate of [Why is it bad to use an iteration variable in a lambda expression](http://stackoverflow.com/questions/227820/why-is-it-bad-to-use-an-iteration-variable-in-a-lambda-expression) – GSerg Feb 09 '17 at 10:15
  • 1
    Why are you using raw threads instead of `Task.Run`? Or `Parallel.For`? Or using a ManualResetEvent instead of a CancellationToken? – Panagiotis Kanavos Feb 09 '17 at 10:26
  • 1
    I suggest you check [How to: Cancel a Parallel.For or ForEach Loop](https://msdn.microsoft.com/en-us/library/ee256691(v=vs.110).aspx) for an example of how easy it is to perform parallel processing and cancellation. You can use a CancellationToken with raw threads as well – Panagiotis Kanavos Feb 09 '17 at 10:28

0 Answers0