2021年4月6日星期二

Why is the using variable disposing itself before leaving the method?

using PuppeteerSharp;  using System;  using System.Threading.Tasks;    namespace Video_Handler  {      public class VideoHost      {          private static bool Is_HTTPS_URL(string url)          {              Uri uriResult;                bool result = Uri.TryCreate(url, UriKind.Absolute, out uriResult) && (uriResult.Scheme == Uri.UriSchemeHttps);              return result;          }            #region BrowserCreationCode          private static async Task FectchBrowserIfItIsNotThere()          {              var browserFetcher = new BrowserFetcher();              await browserFetcher.DownloadAsync();          }          internal static async Task<Page> GetPageAsync(string url, bool isPageInvisible = true, Action<Page> action)          {              if(!Is_HTTPS_URL(url))              {                  throw new ArgumentException($"The url | {url} | is not an https url.");              }              await FectchBrowserIfItIsNotThere();              await using var browser = await Puppeteer.LaunchAsync(                  new LaunchOptions { Headless = isPageInvisible });              await using var page = await browser.NewPageAsync();              await page.GoToAsync(url);              action(page);              return page;          }      }  }  
//Boiler Plate code  async static void Main()  {    Action<Page> action = (page) => Foo(page);    await GetPageAsync("https://google.com", false , action);  }  void Foo(Page p){      await p.EvaluateExpression("//fill google search bar");     await p.EvaluateExpression("//click search button");     await p.WaitForNavigationAsync();     await p.EvaluateExpression("alert("hi")");  }  

I am having an issue where when I send the page variable to the action which takes in a page variable it causes the page or browser variable to be disposed. From what I understand about using, this should only happen if I leave the function's parenthesis. I have read Microsoft's documentation on using and I can't find anything that tells me that the page variable disposes itself upon going to another function within the function the using variable is in.

Also, occasionally the code will be able to evaluate some of the function's expressions but it usually fails by the third. However, if I debug and run step by step, it always fails on the first line. This is what led me to believe it is a disposal issue.

To anyone wondering why I have not just removed the using from browser and page variables and dispose of them myself, I have two reasons. One, I don't have experience with disposing unmanaged code and when I tried to add the dispose to the finalizer/destructor it doesn't work and Secondly, I don't want to write code to do what the language already does for me.

https://stackoverflow.com/questions/66979027/why-is-the-using-variable-disposing-itself-before-leaving-the-method April 07, 2021 at 11:04AM

没有评论:

发表评论