我不太明白之间的差别Task.Wait和await.
我在ASP.NET WebAPI服务中有类似于以下函数:
public class TestController : ApiController
{
public static async Task<string> Foo()
{
await Task.Delay(1).ConfigureAwait(false);
return "";
}
public async static Task<string> Bar()
{
return await Foo();
}
public async static Task<string> Ros()
{
return await Bar();
}
// GET api/test
public IEnumerable<string> Get()
{
Task.WaitAll(Enumerable.Range(0, 10).Select(x => Ros()).ToArray());
return new string[] { "value1", "value2" }; // This will never execute
}
}
Run Code Online (Sandbox Code Playgroud)
哪里Get会僵局.
什么可能导致这个?当我使用阻塞等待而不是await Task.Delay?时,为什么这不会导致问题?
我正在编写一个从网页上抓取数据的C#控制台应用程序.
此应用程序将访问大约8000个网页并刮取数据(每页上的数据格式相同).
我现在正在使用它,没有异步方法,也没有多线程.
但是,我需要它更快.它只使用了大约3%-6%的CPU,我想是因为它花时间等待下载html.(WebClient.DownloadString(url))
这是我的程序的基本流程
DataSet alldata;
foreach(var url in the8000urls)
{
// ScrapeData downloads the html from the url with WebClient.DownloadString
// and scrapes the data into several datatables which it returns as a dataset.
DataSet dataForOnePage = ScrapeData(url);
//merge each table in dataForOnePage into allData
}
// PushAllDataToSql(alldata);
Run Code Online (Sandbox Code Playgroud)
我一直试图多线程,但不知道如何正确开始.我正在使用.net 4.5并且我的理解是异步并且等待4.5以使这更容易编程但我仍然有点迷失.
我的想法是继续制作这条线异步的新线程
DataSet dataForOnePage = ScrapeData(url);
Run Code Online (Sandbox Code Playgroud)
然后当每个人完成时,跑
//merge each table in dataForOnePage into allData
Run Code Online (Sandbox Code Playgroud)
任何人都可以指出我正确的方向如何在.net 4.5 c#中使该行异步,然后让我的合并方法运行完成?
谢谢.
编辑:这是我的ScrapeData方法:
public static DataSet GetProperyData(CookieAwareWebClient webClient, string pageid)
{
var dsPageData …Run Code Online (Sandbox Code Playgroud)