public static void Order_go(string url, string name)
{
// I want to run the line below only once
var driver = new ChromeDriver();
driver.Url = (url);
IWebElement b_login1 = driver.FindElement(By.Id("login"));
b_login1.SendKeys("aa");
IWebElement b_pass1 = driver.FindElement(By.Name("managerPw"));
b_pass1.SendKeys("123");
// Execute each time when it is called
}
我试过
Boolean once = true;
if (once)
{
var driver = new ChromeDriver();
once = false;
}
但是,当我调用此函数时,once
的值再次变为true
。
如何只运行一次此代码?
var driver = new ChromeDriver();
答案 0 :(得分:4)
让driver
成为您班级的static
成员。检查null
。
static ChromeDriver driver;
public static void Order_go(string url, string name)
{
if (driver == null) { driver = new ChromeDriver(); }
driver.Url = (url);
IWebElement b_login1 = driver.FindElement(By.Id("login"));
b_login1.SendKeys("aa");
IWebElement b_pass1 = driver.FindElement(By.Name("managerPw"));
b_pass1.SendKeys("123");
//Execute each time when it is called
}
我会提醒您ChromeDriver
可能不是线程安全的。
答案 1 :(得分:1)
我建议在包含的类中全局初始化它(对不起,如果C#中的术语不正确)。
static ChromeDriver driver = new ChromeDriver();
public static void Order_go(string url, string name)
{
driver.Url = (url);
IWebElement b_login1 = driver.FindElement(By.Id("login"));
b_login1.SendKeys("aa");
IWebElement b_pass1 = driver.FindElement(By.Name("managerPw"));
b_pass1.SendKeys("123");
//Execute each time when it is called
}