我有一个包含配方列表的网页。在我的代码中,我遍历页面并下载每个配方。下面是我在做什么伪代码:使用async/await和Task.Run时不显示特定异常
//This is the Recipe class
//The constructor accepts a link to the recipe
//This method scrapes the recipe
public Task ScrapeAsync(){
return Task.Run(async() => {
string WebPage;
WebRequest request = WebRequest.Create(link);
request.Method = "GET";
using (WebResponse response = await request.GetResponseAsync())
using (StreamReader reader = new StreamReader(response.GetResponseStream())) {
WebPage = await reader.ReadToEndAsync();
}
//Non - async code here which is used to scrape the webpage
}
}
我用Task.Run,因为有两个异步和阻止代码的方法。
//This is the RecipePage class
//This method scrapes the page
public Task GetRecipeListAsync(){
return Task.Run(async() => {
//I get the page using WebRequest and WebResponse in the same way as above
//Non - async/blocking code here which scrapes the page and finds links to recipes. I do await Recipe.ScrapeAsync() somewhere here.
//And I add the recipe objects to a public list in this class
}
}
在窗体中,它循环显示一个页面列表,并执行await RecipePage.GetRecipeList()
等事情。
这里就是for循环是:
private async void go_Click(object sender, EventArgs e){
for (int i = (int)startingPageNUD.Value; i <= (int)finishingPageNUD.Value; ++i) {
RecipePage page = new RecipePage(page + i);
await page.GetRecipeListAsync();
//Some other code here
}
}
我的问题是,每当一个例外,在ScrapeAsync
方法时,Visual Studio发生2013点Application.Run(new Form1())
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
,并告诉我,Reflection.TargetInvocationException
已发生。它不会在我的代码中显示实际的异常。例如,如果我在代码中获得NullReferenceException
,则不会显示该代码。 因此,我不得不编写异步代码和非异步代码,并使用非异步代码进行调试。有什么办法可以解决这个问题吗?
我还有一个问题。我是否以正确的方式使用async/await和Task?
调用'GetRecipeList'的代码是怎样的? – i3arnon
我编辑了这个问题。 –
我知道这样的例外发生,如果抛出的异常无处可去。这可能会发生,如果它是从'await'内部的一个返回'void'而不是'Task'的函数内部引发的。如果你的食谱加载循环在这样的功能? – Nitram