graylobo
graylobo

Reputation: 35

Run specific code within a function only once

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
}

I tried

Boolean once = true;
if (once)
{
    var driver = new ChromeDriver();
    once = false;
}

However, when I call this function, the value of once becomes true again. How can I run this code only once?

var driver = new ChromeDriver();

Upvotes: 0

Views: 2855

Answers (2)

Ousmane D.
Ousmane D.

Reputation: 56423

I'd suggest initialising it globally within the containing class (sorry if the terminology is not correct in 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
}

Upvotes: 1

Daniel A. White
Daniel A. White

Reputation: 190935

Make driver a static member of your class. Check it for 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
}

I would caution you that ChromeDriver may not be thread safe.

Upvotes: 4

Related Questions