我正在迭代一个foreach loop
,其中我正在解析一个字符串,如下所示:
我想在HttpWebRequest
中为我的字符串" imageUrl
"触发并行请求。表示系统的时间4请求和响应类型。(对于我的核心的实用程序)。
我该怎么做?
代码:
foreach (var item in requestData)
{
try
{
string imageUrl = Convert.ToString(item.ImageUrl);
imageUrl = imageUrl.Replace('\r', ' ');
//It is Use for saving at our project location.
string saveLocation =
@AppDomain.CurrentDomain.BaseDirectory + @"Image\someone.jpg";
byte[] imageBytes;
try
{
HttpWebRequest imageRequest =
(HttpWebRequest)WebRequest.Create(imageUrl);
WebResponse imageResponse = imageRequest.GetResponse();
Stream responseStream = imageResponse.GetResponseStream();
using (BinaryReader br = new BinaryReader(responseStream))
{
imageBytes = br.ReadBytes(500000);
br.Close();
}
responseStream.Close();
imageResponse.Close();
FileStream fs = null;
BinaryWriter bw = null;
fs = new FileStream(saveLocation, FileMode.Create);
bw = new BinaryWriter(fs);
bw.Write(imageBytes);
fs.Close();
bw.Close();
id = Convert.ToString(item.Id);
// string ImageUrl= Convert.ToString(dr["ImageUrl"]);
ImageProcess(id);
}
catch (Exception)
{
log.Info("Image Url Wrong!!!");
drCurrentRow = dt.NewRow();
drCurrentRow["Id"] = Convert.ToString(item.Id); ;
drCurrentRow["Label"] = "Error";
drCurrentRow["Score"] = 0;
drCurrentRow["Flag"] = "1";
dt.Rows.Add(drCurrentRow);
//drCurrentRow = dt.NewRow();
dt.AcceptChanges();
}
finally
{
fs.Close();
bw.Close();
}
}
catch (Exception e)
{
log.Info(e);
}
}
BulkInsert();
}
我想在HttpWebRequest
中为我的字符串imageUrl
触发并行请求。
我该怎么做?
答案 0 :(得分:1)
Parallel.ForEach(requestData, item =>
{
//your code
});
答案 1 :(得分:0)
您可以使用Parallel.ForEach()或by Using async and await
Parallel.ForEarch(requestData, item => {
//web request
});