我正在努力。Dispose()
和Chromium正在构建并崩溃我的计算机,因为这是一个持续数天的过程。
但是,我不能把放进去。Dispose()
在return
之后,因为它将不可访问,如果我将它放在return
之前,则内容字符串将变得过时。
var docBContent = await renderHtmlAsync(url2);
fromDoc.LoadHtml(docBContent);
public static async Task<string> renderHtmlAsync(string url2)
{
await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultChromiumRevision);
Browser browser = await Puppeteer.LaunchAsync(new LaunchOptions
{
Headless = true
});
var page = await browser.NewPageAsync();
page.DefaultTimeout = 0;
var navigation = new NavigationOptions
{
Timeout = 0,
WaitUntil = new[] {
WaitUntilNavigation.DOMContentLoaded }
};
await page.GoToAsync(url2, navigation);
var content = page.GetContentAsync();
return await content;
}
我该如何解决这个问题?
您可以使用使用
块:
public static async Task<string> renderHtmlAsync(string url2)
{
await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultChromiumRevision);
using (Browser browser = await Puppeteer.LaunchAsync(new LaunchOptions
{
Headless = true
}))
{
var page = await browser.NewPageAsync();
page.DefaultTimeout = 0;
var navigation = new NavigationOptions
{
Timeout = 0,
WaitUntil = new[] {
WaitUntilNavigation.DOMContentLoaded }
};
await page.GoToAsync(url2, navigation);
var content = page.GetContentAsync();
return await content;
}
}
这就像:
var myObject = new DispoableObject();
try
{
// insert code
return result;
}
finally
{
myObject.Dispose();
}
始终执行finally中的代码,即使在try块中抛出异常也是如此。