Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Vb.net 使用异步等待递增_Vb.net_Async Await - Fatal编程技术网

Vb.net 使用异步等待递增

Vb.net 使用异步等待递增,vb.net,async-await,Vb.net,Async Await,我在VS2012中使用Async Await,并尝试在使用多个线程时增加一个值 我知道我可以使用Interlocked.Increment使I+=1线程安全或使用同步锁 这给了我这个密码 Imports System.Threading Module Module1 Private incre As New Incrementing Sub Main() Console.WriteLine("Starting") Const numb

我在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
但是它看起来不太漂亮,任务。跑步对一个人来说似乎很奇怪。有更好的方法吗

在我看来,螺纹方式没有那么笨重

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