0

I have defined a class like this:

class visualDisplay : IDisplay
{
    //Fields

    Form1 _form;
    Thread _displayThread;

    //Methods

    public visualDisplay()
    {
        _displayThread = new Thread(new ThreadStart(initialize));
        _displayThread.Start();
        //initialize();
    }

    [STAThread]
    void initialize()
    {

        Application.EnableVisualStyles();

        Application.SetCompatibleTextRenderingDefault(false);

        Application.Run( _form = new Form1());
    }
}

I want to make an instance of a form and use it. But if call the initialize() method in the main thread (As it is commented above), I won't be able to run the rest of my code until I close the form. On the other hand if I call it in the new thread which I defined (displayThread), It will be like there is no Form at all and when I want to use _form, I'll get the Null reference exception as below:

Object reference not set to an instance of an object.

So is there any way to fix this?

whoAmI
  • 318
  • 3
  • 14
  • [What is a `NullReferenceException` and how do I fix it?](http://stackoverflow.com/q/4660142/447156) – Soner Gönül Mar 08 '16 at 08:10
  • Well lets walk trough this code - you assign _form in parallel thread, in the meantime you continue with execution and (probably) access the _form variable - it will be null until the initialize() method finishes. Also your _form variable is not marked as volatile. – Ondrej Svejdar Mar 08 '16 at 08:25
  • Your code working fine.. then what's the problem? – Faraz Ahmed Mar 08 '16 at 08:33
  • No it's not working fine. I think what I really want is to create an instance of a form in my own class and control it myself. I want it to display whatever I want whenever I want. That means some other piece of code should do the processing and tell '_form' to display it. I don't want my code to run by any event like '_form_load' event or 'button1_Click' event because the form should not control anything. it should just display when I tell him so. – whoAmI Mar 08 '16 at 08:49
  • Something else that may solve my problem. Shouldn't `[STAThread]` take care of all multithreading stuff like the **Cross-thread operation** ? But it's not working so I have to use a new thread and then I'll have **Cross-thread operation** problems. – whoAmI Mar 08 '16 at 09:18

0 Answers0