are there any drawbacks or risks of using Parallel.Foreach with WebClient() inside my asp.net mvc web application

后端 未结 2 808
被撕碎了的回忆
被撕碎了的回忆 2021-02-11 02:52

I am working on an asp.net MVC-5 web application, and based on some articles i read that i should not use Parallel methods inside web servers and inside .net web applications es

2条回答
  •  太阳男子
    2021-02-11 03:33

    Take a look at:
    object syncObj = new object();
    lock(syncObj)

    try
    {
        using (WebClient wc = new WebClient()) 
        {
            string url = currentURL + "resources?AUTHTOKEN=" + pmtoken;
            var json = await wc.DownloadStringTaskAsync(url);
            resourcesinfo = JsonConvert.DeserializeObject(json);
        }
    
        object syncObj = new object();  // create sync object
        Parallel.ForEach(resourcesinfo.operation.Details, new ParallelOptions { MaxDegreeOfParallelism = 7 }, (c) =>
        {
            ResourceAccountListInfo resourceAccountListInfo = new ResourceAccountListInfo();
            using (WebClient wc = new WebClient()) 
            {
                string url = currentURL + "resources/" + c.RESOURCEID + "/accounts?AUTHTOKEN=" + pmtoken;
                string tempurl = url.Trim();
    
                var json =  wc.DownloadString(tempurl);
                resourceAccountListInfo = JsonConvert.DeserializeObject(json);
            }
    
            lock(syncObj)  // lock using sync object
            {
                PMresourcesOnly.Add(resourceAccountListInfo.operation.Details);
            }
        });//end of foreach
    
        return PMresourcesOnly.ToList();
    }
    catch (Exception e)
    {
    }
    

提交回复
热议问题