-2

For some reason my windows form closes immediately after I run the program. I can see the form for about a second and then it closes. Here is my form load method

private void Form1_Load(object sender, EventArgs e)
    {
        CustGen = new CustomerGenerator(); 
        fuelType = null; 

        //set data on form initialization.
        unleadedtank = 10000f;
        dieseltank = 10000f;
        u_price = 136.9f;
        d_price = 152.2f;

        //event subscriptions

        CustGen.CustomerReady += CustomerReadySub; //Subscribes to ready event
        CustGen.PumpProgress += PumpProgressSub; //subscribes to progress event
        CustGen.PumpingFinished += PumpingFinishedSub; //subscribes to stop event

    }

and here is my program.cs for that particular form, although this is automatically generated I wasn't sure if it was needed.

        [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }

This is within the customerGenerator class

  public class CustomerGenerator
{
    public CustomerGenerator();

    public event CustomerGenerator.CustomerReadyHandler CustomerReady;
    public event CustomerGenerator.PumpingFinishedHandler PumpingFinished;
    public event CustomerGenerator.PumpProgressHandler PumpProgress;

    public void ActivatePump();
    public void Start();

    public delegate void CustomerReadyHandler(object sender, CustomerReadyEventArgs e);

    public delegate void PumpingFinishedHandler(object sender, EventArgs e);

    public delegate void PumpProgressHandler(object sender, PumpProgressEventArgs e);
}

I have ran the program and came across this after carrying out what one of the users said below in the comments.

 public void CustomerReadySub(object sender, CustomerReadyEventArgs fuel)
    {
        string CustReady = null;

        //checks what fuel is chosen and then activates the pump
        fuelType = fuel.SelectedFuel.ToString();

        if (!String.IsNullOrEmpty(fuelType))
        {
            fTypeLabel.Text = fuelType;

It is this line that is throwing the exception. Also it says "Cross-thread operation not valid: Control 'Form1' accessed from a thread other than the thread it was created on."

fuelType = fuel.SelectedFuel.ToString();

Thanks

4

1 回答 1

1

它还说“跨线程操作无效:控件'Form1'从创建它的线程以外的线程访问。”

使用以下模式访问表单上的控件:

private void MyHandler(object sender, EventArgs e) {
  if (InvokeRequired) Invoke(new EventHandler(MyHandler), sender, e);
  else {
    // code to handle the event
  }
}

当您侦听从某个线程上执行的某些对象生成的事件时,处理该事件的代码将在该线程上运行。每当您从创建这些对象的线程以外的线程访问 UI 对象时,您都会遇到异常。InvokeRequired 检查您是否在 UI 线程上运行,如果不是,则调用该方法以在 UI 线程上运行。这使您可以安全地访问控件。

于 2013-04-21T23:16:32.550 回答