出于某种原因,我的Windows窗体在运行程序后立即关闭。我可以看到表格大约一秒钟,然后它关闭。这是我的表单加载方法
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
}
这是我的program.cs,用于该特定表单,虽然这是自动生成的,但我不确定是否需要它。
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
这是在customerGenerator类
中 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);
}
我已经运行了该程序并在执行了以下用户在评论中所说的内容后遇到了这个问题。
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;
正是这条线引发了异常。它还说“跨线程操作无效:控制'Form1'从一个线程访问,而不是创建它的线程。”
fuelType = fuel.SelectedFuel.ToString();
由于
答案 0 :(得分: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线程上运行。这允许您安全地访问控件。