我在 VS2012 中使用 Async-Await 并尝试在使用多个线程时增加一个值。
我知道我可以使用 Interlocked.Increment 使 i += 1 线程安全或使用同步锁。
这给了我这个代码。
Imports System.Threading
Module Module1
Private incre As New Incrementing
Sub Main()
Console.WriteLine("Starting")
Const numberofthreads As Integer = 20
Dim ts(numberofthreads) As Task(Of Integer)
For i = 0 To numberofthreads
ts(i) = count()
Next
Task.WaitAll(ts)
For i = 0 To numberofthreads
Console.WriteLine(ts(i).Result)
Next
Console.ReadLine()
End Sub
Async Function count() As Task(Of Integer)
Await Task.Run(Sub()
For i = 1 To 1000
incre.Add()
Thread.Sleep(1)
Next
End Sub)
Return incre.Read()
End Function
Public Class Incrementing
Private i As Integer = 0
Public Sub Add()
Interlocked.Increment(i)
End Sub
Public Function Read() As Integer
Return i
End Function
End Class
End Module
但它看起来不是很漂亮,Task.Run 对一个人来说似乎很奇怪。有没有更好的方法来做到这一点?
在我看来,螺纹方式不那么笨拙。
Imports System.Threading
Module Module1
Private incre As New Incrementing
Sub Main()
For i = 0 To 20
Dim t1 As New Thread(AddressOf count)
t1.IsBackground = True
t1.Start()
Next
Console.ReadLine()
End Sub
Sub count()
For i = 1 To 1000
incre.Add()
Thread.Sleep(1)
Next
Console.WriteLine(incre.Read())
End Sub
Public Class Incrementing
Private i As Integer = 0
Public Sub Add()
Interlocked.Increment(i)
End Sub
Public Function Read() As Integer
Return i
End Function
End Class
End Module