是否可以使用多線程程序來加速我的程序進程?vb.net多線程加速我的程序執行
我的程序是以下
1-通過這個號碼一個遠程服務器 3-將結果存儲在文本文件
問題基本上,當我查詢生成的隨機數 2-查詢遠程服務器需要10秒 而不是等待這段時間我想生成100或1000個號碼,並分別發送它們,然後當結果出來時我將它們保存在緩衝區中並稍後保存爲文本
任何幫助或想法在那裏面 ?
是否可以使用多線程程序來加速我的程序進程?vb.net多線程加速我的程序執行
我的程序是以下
1-通過這個號碼一個遠程服務器 3-將結果存儲在文本文件
問題基本上,當我查詢生成的隨機數 2-查詢遠程服務器需要10秒 而不是等待這段時間我想生成100或1000個號碼,並分別發送它們,然後當結果出來時我將它們保存在緩衝區中並稍後保存爲文本
任何幫助或想法在那裏面 ?
Module Module1
Sub main()
Randomize()
Dim r = New Random
Dim rLock = New Object
Dim results As New Concurrent.ConcurrentBag(Of Tuple(Of Integer, String))
Dim getRandom = New Func(Of Integer)(Function()
SyncLock rLock
Return r.Next(0, Integer.MaxValue)
End SyncLock
End Function)
' total number of loops
' v
System.Threading.Tasks.Parallel.For(0, 100, Sub(i)
Dim aRandom = getRandom()
'process the query
Dim output = "-server-response-" 'or whatever the outcome of processing
results.Add(New Tuple(Of Integer, String)(aRandom, output))
End Sub)
For Each itm In results
Console.WriteLine(itm.Item1 & vbTab & itm.Item2)
Next
End Sub
End Module
我會看看使用微軟的Reactive Framework(NuGet Rx-Main
)。
這將是你的代碼:
Dim rnd = New Random()
Dim query = _
From i In Observable.Range(0, 1000) _
From n In Observable.Start(Function() rnd.Next()) _
From r in Observable.Start(Function (x) CallWebService(x)) _
Select r
File.WriteAllLines(filePath, _
String.Join(Environment.NewLine, query.ToEnumerable()))
與最大吞吐量後臺線程中運行。
完成!
是的,你可以通過多線程,但你的意思是查詢?你可以發佈嗎? – 2014-08-28 11:00:53
我基本上發送號碼,例如1087673和服務器返回全名 – user2085339 2014-08-28 11:12:34
使用多線程意味着您的程序不會等待每個請求完成,然後開始下一個請求。這是否會更快是未知的,因爲服務器可能一次只能處理一個請求 – 2014-08-28 11:35:52