问题描述
我百度了下,关于这方面的知识很少,特来请教csdn的各位大牛多线程post请求多个不同网页,然后返回其页面的源码,我的代码如下。遇到的问题:我加入多线程不行。。。不知道是不是我的代码错了ImportsSystemImportsSystem.IOImportsSystem.NetImportsSystem.TextImportsSystem.ThreadingPublicClassForm1DimiAsStringDimiiAsStringDimtAsThreadPrivateDelegateSubvoiddelegate(ByRefiAsString,ByRefiiAsString)PrivateSubForm1_Load(senderAsObject,eAsSystem.EventArgs)HandlesMe.Loadi="http://www.baidu.com"'这个是目标地址ii="xxx"'xxx是用户名和密码EndSubPrivateSubButton1_Click(senderAsSystem.Object,eAsSystem.EventArgs)HandlesButton1.Clickt=NewThread(AddressOftest)t.Start()EndSubPrivateSubupdateui(ByRefiAsString,ByRefiiAsString)Me.TextBox1.Text=postHtml(i,ii)EndSubPrivateSubtest()Me.Invoke(Newvoiddelegate(AddressOfupdateui),i,ii)t.Abort()EndSubFunctionpostHtml(ByRefhtmlUrlAsString,ByRefhtmlDateAsString)'这个是post请求函数DimrequestAsHttpWebRequest=WebRequest.Create(htmlUrl)DimfanhuiAsString'SettheMethodpropertyoftherequesttoPOST.request.Method="POST"'CreatePOSTdataandconvertittoabytearray.DimpostDataAsString=htmlUrlDimbyteArrayAsByte()=Encoding.UTF8.GetBytes(htmlDate)'SettheContentTypepropertyoftheWebRequest.request.ContentType="application/x-www-form-urlencoded"'SettheContentLengthpropertyoftheWebRequest.request.ContentLength=byteArray.Length'Gettherequeststream.DimdataStreamAsStream=request.GetRequestStream()'Writethedatatotherequeststream.dataStream.Write(byteArray,0,byteArray.Length)'ClosetheStreamobject.dataStream.Close()'Gettheresponse.DimresponseAsWebResponse=request.GetResponse()'Displaythestatus.'TextBox1.Text=(CType(response,HttpWebResponse).StatusDescription)'Getthestreamcontainingcontentreturnedbytheserver.dataStream=response.GetResponseStream()'OpenthestreamusingaStreamReaderforeasyaccess.DimreaderAsNewStreamReader(dataStream)'Readthecontent.DimresponseFromServerAsString=reader.ReadToEnd()'Displaythecontent.fanhui=(responseFromServer)Returnfanhui'Cleanupthestreams.Console.ReadLine()reader.Close()dataStream.Close()response.Close()EndFunctionEndClass'
再附上代码高清图
解决方案
解决方案二:
UI控件(Me.TextBox1.Text)不是线程安全的。参考
解决方案三:
要委托PrivateSubupdateui(ByRefiAsString,ByRefiiAsString)Me.TextBox1.Text=postHtml(i,ii)EndSubPrivateSubtest()DimwtAsNewMethodInvoker(AddressOfupdateui,i,ii)BeginInvoke(wt)EndSub
解决方案四:
两个办法,1.不让VB检查线程的安全性form_load加入Control.CheckForIllegalCrossThreadCalls=false2.用invoke委托,这是标准方法