當前位置: 首頁>>代碼示例>>VB.NET>>正文


VB.NET TaskFactory.StartNew方法代碼示例

本文整理匯總了VB.NET中System.Threading.Tasks.TaskFactory.StartNew方法的典型用法代碼示例。如果您正苦於以下問題:VB.NET TaskFactory.StartNew方法的具體用法?VB.NET TaskFactory.StartNew怎麽用?VB.NET TaskFactory.StartNew使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在System.Threading.Tasks.TaskFactory的用法示例。


在下文中一共展示了TaskFactory.StartNew方法的6個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的VB.NET代碼示例。

示例1: Example

' 導入命名空間
Imports System.Collections.Generic
Imports System.Threading
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim cts As New CancellationTokenSource()
      Dim token As CancellationToken = cts.Token
      Dim tasks As New List(Of Task)()
      Dim rnd As New Random()
      Dim lockObj As New Object()
      Dim words6() As String = { "reason", "editor", "rioter", "rental",
                                 "senior", "regain", "ordain", "rained" }

      For Each word6 in words6
         tasks.Add(Task.Factory.StartNew( Sub(word)
                                              Dim chars() As Char = word.ToString().ToCharArray()
                                              Dim order(chars.Length - 1) As Double
                                              Dim wasZero As Boolean = False
                                              SyncLock lockObj
                                                 For ctr As Integer = 0 To order.Length - 1
                                                    order(ctr) = rnd.NextDouble()
                                                    If order(ctr) = 0 Then
                                                       If Not wasZero Then
                                                          wasZero = True
                                                       Else
                                                          cts.Cancel()
                                                       End If
                                                    End If
                                                 Next
                                              End SyncLock
                                              token.ThrowIfCancellationRequested()
                                              Array.Sort(order, chars)
                                              Console.WriteLine("{0} --> {1}", word,
                                                                new String(chars))
                                          End Sub, word6))
      Next
      Try
         Task.WaitAll(tasks.ToArray())
      Catch e As AggregateException
         For Each ie In e.InnerExceptions
            If TypeOf ie Is OperationCanceledException
               Console.WriteLine("The word scrambling operation has been cancelled.")
               Exit For
            Else
               Console.WriteLine(ie.GetType().Name + ": " + ie.Message)
            End If
         Next
      Finally
         cts.Dispose()
      End Try
   End Sub
End Module
開發者ID:VB.NET開發者,項目名稱:System.Threading.Tasks,代碼行數:54,代碼來源:TaskFactory.StartNew

輸出:

regain --> irnaeg
ordain --> rioadn
reason --> soearn
rained --> rinade
rioter --> itrore
senior --> norise
rental --> atnerl
editor --> oteird

示例2: Example

' 導入命名空間
Imports System.Collections.Generic
Imports System.IO
Imports System.Threading
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim tokenSource As New CancellationTokenSource()
      Dim token As CancellationToken = tokenSource.Token
      Dim files As New List(Of Tuple(Of String, String, Long, Date))()

      Dim t As Task = Task.Factory.StartNew( Sub()
                                   Dim dir As String = "C:\Windows\System32\"
                                   Dim obj As New Object()
                                   If Directory.Exists(dir)Then
                                      Parallel.ForEach(Directory.GetFiles(dir), 
                                         Sub(f)
                                            If token.IsCancellationRequested Then
                                               token.ThrowIfCancellationRequested()
                                            End If  
                                            Dim fi As New FileInfo(f)
                                            SyncLock(obj)
                                              files.Add(Tuple.Create(fi.Name, fi.DirectoryName, fi.Length, fi.LastWriteTimeUtc))          
                                            End SyncLock
                                         End Sub)
                                   End If
                                End Sub, token)
      tokenSource.Cancel()
      Try
         t.Wait() 
         Console.WriteLine("Retrieved information for {0} files.", files.Count)
      Catch e As AggregateException
         Console.WriteLine("Exception messages:")
         For Each ie As Exception In e.InnerExceptions
            Console.WriteLine("   {0}:{1}", ie.GetType().Name, ie.Message)
         Next
         Console.WriteLine()
         Console.WriteLine("Task status: {0}", t.Status)       
      Finally
         tokenSource.Dispose()
      End Try
   End Sub
End Module
開發者ID:VB.NET開發者,項目名稱:System.Threading.Tasks,代碼行數:44,代碼來源:TaskFactory.StartNew

輸出:

Exception messages:
TaskCanceledException: A task was canceled.

Task status: Canceled

示例3: Example

' 導入命名空間
Imports System.Collections.Generic
Imports System.Threading.Tasks

Public Module Example
   Public Sub Main()
      Dim rnd As New Random()
      Dim tasks As New List(Of Task)
      ' Execute the task 10 times.
      For ctr As Integer = 1 To 9
         tasks.Add(Task.Factory.StartNew(Sub()
                                            Dim utf32 As Integer
                                            SyncLock(rnd)
                                               ' Get UTF32 value.
                                               utf32 = rnd.Next(0, &hE01F0)
                                            End SyncLock
                                            ' Convert it to a UTF16-encoded character.
                                            Dim utf16 As String = Char.ConvertFromUtf32(utf32)
                                            ' Display information about the character.
                                            Console.WriteLine("0x{0:X8} --> '{1,2}' ({2})", 
                                                              utf32, utf16, ShowHex(utf16))
                                         End Sub))                           
      Next
      Task.WaitAll(tasks.ToArray()) 
   End Sub
   
   Private Function ShowHex(value As String) As String
      Dim hexString As String = Nothing
      ' Handle only non-control characters.
      If Not Char.IsControl(value, 0) Then
         For Each ch In value
            hexString += String.Format("0x{0} ", Convert.ToUInt16(ch))
         Next
      End If   
      Return hexString.Trim()
   End Function
End Module
開發者ID:VB.NET開發者,項目名稱:System.Threading.Tasks,代碼行數:37,代碼來源:TaskFactory.StartNew

輸出:

0x00097103 --> '򗄃' (0x55836 0x56579)
0x000A98A1 --> '򩢡' (0x55910 0x56481)
0x00050002 --> '񐀂' (0x55552 0x56322)
0x0000FEF1 --> 'ﻱ' (0x65265)
0x0008BC0A --> '򋰊' (0x55791 0x56330)
0x000860EA --> '򆃪' (0x55768 0x56554)
0x0009AC5A --> '򚱚' (0x55851 0x56410)
0x00053320 --> '񓌠' (0x55564 0x57120)
0x000874EF --> '򇓯' (0x55773 0x56559)

示例4: Example

' 導入命名空間
Imports System.Collections.Generic
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim tasks As New List(Of Task)()
      Dim rnd As New Random()
      Dim lockObj As New Object()
      Dim words6() As String = { "reason", "editor", "rioter", "rental",
                                 "senior", "regain", "ordain", "rained" }

      For Each word6 in words6
         tasks.Add(Task.Factory.StartNew( Sub(word)
                                              Dim chars() As Char = word.ToString().ToCharArray()
                                              Dim order(chars.Length - 1) As Double
                                              SyncLock lockObj
                                                 For ctr As Integer = 0 To order.Length - 1
                                                    order(ctr) = rnd.NextDouble()
                                                 Next
                                              End SyncLock
                                              Array.Sort(order, chars)
                                              Console.WriteLine("{0} --> {1}", word,
                                                                new String(chars))
                                          End Sub, word6))
      Next
      Task.WaitAll(tasks.ToArray())
   End Sub
End Module
開發者ID:VB.NET開發者,項目名稱:System.Threading.Tasks,代碼行數:29,代碼來源:TaskFactory.StartNew

輸出:

regain --> irnaeg
ordain --> rioadn
reason --> soearn
rained --> rinade
rioter --> itrore
senior --> norise
rental --> atnerl
editor --> oteird

示例5: AdditionTester

' 導入命名空間
Imports System.Threading.Tasks

Module AdditionTester
   Public Sub Main()
      Dim rnd As New Random()
      Dim tasks(1) As Task(Of Integer)
      Dim obj As New Object()
      
      Do While True
         For ctr As Integer = 0 To 1
            tasks(ctr) = Task.Factory.StartNew(Function()
                                                  Dim i As Integer
                                                  SyncLock(obj)
                                                     i = rnd.Next(101)
                                                  End SyncLock
                                                  Return i
                                               End Function)
         Next
         Task.WaitAll(tasks)
         Dim n1 As Integer = tasks(0).Result
         Dim n2 As Integer = tasks(1).Result
         Dim result As Integer = n1 + n2
         Dim validInput As Boolean = False
         Do While Not validInput
            ShowMessage(n1, n2)
            Dim userInput As String = Console.ReadLine()
            ' Process user input.
            If userInput.Trim().ToUpper = "X" Then Exit Sub
            Dim answer As Integer
            validInput = Int32.TryParse(userInput, answer)
            If Not validInput Then
               Console.WriteLine("Invalid input. Try again, but enter only numbers. ")
            Else If answer = result Then
               Console.WriteLine("Correct!")
            Else
               Console.WriteLine("Incorrect. The correct answer is {0}.", result)
            End If
         Loop
      Loop
   End Sub
   
   Private Sub ShowMessage(n1 As Integer, n2 As Integer)
      Console.WriteLine()
      Console.WriteLine("Enter 'x' to exit...")
      Console.Write("{0} + {1} = ", n1, n2)
   End Sub
End Module
開發者ID:VB.NET開發者,項目名稱:System.Threading.Tasks,代碼行數:48,代碼來源:TaskFactory.StartNew

輸出:

Enter 'x' to exit...
15 + 11 = 26
Correct!

Enter 'x' to exit...
75 + 33 = adc
Invalid input. Try again, but enter only numbers.

Enter 'x' to exit...
75 + 33 = 108
Correct!

Enter 'x' to exit...
67 + 55 = 133
Incorrect. The correct answer is 122.

Enter 'x' to exit...
92 + 51 = 133
Incorrect. The correct answer is 143.

Enter 'x' to exit...
81 + 65 = x

示例6: Main

' 導入命名空間
Imports System.Collections.Generic
Imports System.Numerics
Imports System.Threading
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim rnd As New Random()
      Dim tasks As New List(Of Task(Of BigInteger()))
      Dim source As New CancellationTokenSource
      Dim token As CancellationToken = source.Token
      For ctr As Integer = 0 To 1
         Dim start As Integer = ctr
         tasks.Add(Task.Run(Function()
                               Dim sequence(99) As BigInteger
                               sequence(0) = start
                               sequence(1) = 1
                               For index As Integer = 2 To sequence.GetUpperBound(0)
                                  token.ThrowIfCancellationRequested()
                                  sequence(index) = sequence(index - 1) + sequence(index - 2)
                               Next
                               Return sequence
                            End Function, token))
      Next
      If rnd.Next(0, 2) = 1 Then source.Cancel
      Try
         Task.WaitAll(tasks.ToArray())
         For Each t In tasks
            Console.WriteLine("{0}, {1}...{2:N0}", t.Result(0), t.Result(1),
                              t.Result(99))
         Next
      Catch e As AggregateException
         For Each ex In e.InnerExceptions
            Console.WriteLine("{0}: {1}", ex.GetType().Name, ex.Message)
         Next
      End Try
   End Sub
End Module
開發者ID:VB.NET開發者,項目名稱:System.Threading.Tasks,代碼行數:39,代碼來源:TaskFactory.StartNew

輸出:

0, 1...218,922,995,834,555,169,026
1, 1...354,224,848,179,261,915,075
or the following output:
TaskCanceledException: A task was canceled.
TaskCanceledException: A task was canceled.


注:本文中的System.Threading.Tasks.TaskFactory.StartNew方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。