C# 多线程调用WebClient速度变慢的问题
不使用线程速度很快,创建多个线程序调用时就变得很慢,不知什么地方出问题了,麻烦高手帮下!
代码如下
private string getHtml(string url)
{
string restr = "";
WebClient myWebClient = new WebClient();
try
{
byte[] myDataBuffer = myWebClient.DownloadData(url);
restr = Encoding.Default.GetString(myDataBuffer);
myDataBuffer = null;
}
}
catch (Exception ex)
{
restr = "";
ErrlogIt("getHtml err:" + ex.Message);
}
finally
{
myWebClient.Dispose();
}
return restr;
}
private void timerMO_Tick(object sender, EventArgs e)
{
this.timerMO.Enabled = false;
if (putmoBool)
{
thMO = new Thread(putMO);
thMO.Name = "thMO";
thMO.Start();
frmMain.CheckForIllegalCrossThreadCalls = false;
}
this.timerMO.Interval = cInterval;
this.timerMO.Enabled = true;
}
private void putMO()
{
putmoBool = false;
DataSet dsMoUrl = new DataSet();
try
{
string sqlUrl = "select corpid,subnumber,mourl,moflag from corpurl where len(mourl)>10 and moflag<=0 order by moflag desc";
dsMoUrl = Query(sqlUrl);
}
catch (Exception ex)
{
ErrlogIt(ex.Message);
}
if (dsMoUrl == null)
{
putmoBool = true;
return;
}
if (dsMoUrl.Tables.Count == 0)
{
putmoBool = true;
return;
}
try
{
actionMo(dsMoUrl);
}
catch (Exception ex)
{
ErrlogIt(ex.Message);
}
finally
{
dsMoUrl.Dispose();
putmoBool = true;
}
}
private void actionMo(DataSet dsMoUrl)
{
bool canGo = true;
int ct = 0;
int i = 0;
ct = dsMoUrl.Tables[0].Rows.Count;
while (i < ct && canGo)
{
DataRow dr = dsMoUrl.Tables[0].Rows[i];
string corpid = dr["corpid"].ToString();
string subnumber = dr["subnumber"].ToString();
string mourl = dr["mourl"].ToString();
int moflag = int.Parse(dr["moflag"].ToString());
DataSet dsMoList = new DataSet();
if (canGo)
{
try
{
string QuerySql = "select top " + pushSpeed.ToString() + " * from mo.motocorp where corpID=" + corpid + " and subnumber=" + subnumber + " order by moflag asc,moid asc";
dsMoList = Query(QuerySql);
}
catch (Exception ex)
{
canGo = false;
ErrlogIt(ex.Message);
}
}
if (canGo)
{
int j = 0;
int listCt = dsMoList.Tables[0].Rows.Count;
string urlResp = "";
string respValue = "";
while (j < listCt && canGo)
{
DataRow listDr = dsMoList.Tables[0].Rows[j];
string moid = listDr["moid"].ToString();
string sUrl = mourl + "?msgFormat=1&moID=" + moid
try
{
urlResp = getHtml(sUrl);
}
catch
{
urlResp = "";
logIt("失败!");
this.labErr.Text = (int.Parse(this.labErr.Text.ToString()) + 1).ToString();
}
try
{
if (urlResp.Length < 3)
urlResp = urlResp + " ";
respValue = urlResp.Substring(0, 3);
if (respValue.Trim() == "100")
{
logIt("moOK!");
}
else
{
logIt("moNO!");
canGo = false;
}
}
catch (Exception ex)
{
ErrlogIt(ex.Message);
}
j = j + 1;
}
}
dsMoList.Dispose();
i = i + 1;
}
}