0

I'm fairly new to programming, so sorry if I mess some of the words up, also I guess this question is probably really stupid.

Anyways, I'm trying to control a C# browser window from a different thread.

The program has 2 windows. A console and the Form with the browser window.

namespace CodeSnippet
{
    public partial class browserwindow : Form
    {

        public browserwindow()
        {
            InitializeComponent();

            //for the browser form to open, the console HAS to run in a seperate thread
            Thread ConsoleThread = new Thread(new ThreadStart(TheConsole));
            ConsoleThread.Start();

        }

        public static void TheConsole()
        {
            while(true)
            {
                //read the input
                string rawinput = Console.ReadLine();
                string input = rawinput.ToLower();


                //look for commands
                if(input == "website")
                {
                    Console.WriteLine("Waiting...");
                    string website = Console.ReadLine();

                    //TheBrowser is the name of the browser window
                    TheBrowser.Navigate(website);

                    Console.WriteLine("done!");
                }
            }
        }

The "TheBrowser.Navigate" does not work in this piece of code. However, if I remove the "static" on "TheConsole()" the code works perfectly fine.

Now my question is: Is it 'okay' to remove the static from the function?

dronex
  • 3
  • 1
  • 3
  • 1
    *"Is it 'okay' to remove the static from the function"* - [see the difference](http://stackoverflow.com/q/13155474/1997232) – Sinatr Sep 29 '16 at 13:44
  • 9
    Multithreading is not a good topic for beginner programmers. There is much subtlety. To address your specific question: your question is "I am going to make a program change I don't understand, is that OK?" No. **Understand the change before you make it.** Then make the change. – Eric Lippert Sep 29 '16 at 13:45

1 Answers1

1

static means you call it from the class, so browserwindow.Navigate(); would compile. Non-static means it has to be called from an instance of the class, so TheBrowserWindow.Navigate(); compiles successfully when the method is not static. That means you are telling that particular instance to invoke its Navigate method.

A non-static method has special access to the particular instance that called it, so it can say this.x to access the variable x of that instance, or this to reference instance itself.

You have not posted what the method Navigate does, but it sounds like it is appropriate for it to be non-static because it sounds like you are telling that particular instance of the browser object to navigate to a page. So it is probably better that you made it non-static. But if you post the code from that method you could get a better answer.

Chris Rollins
  • 550
  • 3
  • 9