使用async-await增加

时间:2012-11-04 08:14:59

标签: vb.net async-await

我在VS2012中玩Async-Await,并尝试在使用多个线程时增加一个值。

我知道我可以使用Interlocked.Increment来使i + = 1线程安全或使用synclock。

这给了我这段代码。

    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

0 个答案:

没有答案