I have some code that I need to fix to print "Hello World!". For some reason it prints the letters all scrambled.
Sub Main()
Dim s As String = "Hello World!"
Parallel.For(0, s.Length, Sub(i)
Console.Write(s(i))
开发者_运维知识库 End Sub)
Console.Read()
End Sub
Any suggestions?
Sub Main()
Console.Write("Hello World!")
End Sub
If you really must print one character at a time, you could write:
Sub Main()
dim s as string = "Hello World!"
dim i as integer
for i=0 to s.length-1
Console.Write(s(i))
end for
End Sub
The whole point of parallel execution is that they are done in parallel, not sequentially. Parallel execution doesn't make sense for this task because order does matter very much.
With asynchronous/parallel execution, each task is split to run in parallel with others and does not wait on any prior tasks to complete. In your case, some of the later-queued tasks are completing before ones that were queued before them and that is reordering the letters in seemingly random order.
Perhaps you could use the ParallelOptions parameter and specify the degree of parallelism you require. In this case you don't require parallelism.
Sub Main()
Dim s As String = "Hello World!"
Dim p As New ParallelOptions()
p.MaxDegreeOfParallelism = 1
p.TaskScheduler = Nothing
p.CancellationToken = Nothing
Parallel.For(0, s.Length, p, Sub(i)
Console.Write(s(i))
End Sub)
Console.Read()
End Sub
精彩评论