本文介绍了停止运行和关闭表单的任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我有一个任务,即在我的表单中做一些工作,我在表单加载中调用它,因为 bool isRunning = false; 秒表timeOutWatchA =新秒表(); private void Form1_Load(object sender,EventArgs e) { Task.Factory.StartNew(()=> { if(Settings) .CurrentSettings.EnableA) WeightReadingThreadA(); }); } private void WeightReadingThreadA() { SerialPort portA = new SerialPort(); TimeOutA(); timeOutWatchA.Start(); 尝试 { portA.Open(); if(portA.IsOpen) { while(isRunning) { //这里有什么 这个.Invoke(new Action(()=> { try { //显示结果到UI } catch(例外) {} })); timeOutWatchA.Reset(); timeOutWatchA.Start(); } } } catch(Exception ex) { MessageBox.Show(ex.Message); } } private void TimeOutA() { Task.Factory.StartNew(()=> { while( isRunning) { Thread.Sleep(1000); if((timeOutWatchA.ElapsedMilliseconds / 1000)> 3) { this.Invoke(new Action (()=> {尝试 { //向UI显示消息 //这是我获得 //错误的地方当我尝试 //关闭表格} catch(例外) {} })); } } }); } private void BtnClose_Click(object sender,EventArgs e) { isRunning = false; this.Close(); } 当我尝试关闭表单时,我收到错误"'无法在控件上调用Invoke或BeginInvoke,直到窗口句柄已创建"。我的问题是如何阻止此错误,以便我可以很好地关闭表单。我已经尝试将变量 isRunning设置为false,然后我关闭表单但这不起作用 如果你认为你可以实现它解决方案 I have a task thats doing some work in my form and I call it in the form load like sobool isRunning = false; Stopwatch timeOutWatchA = new Stopwatch(); private void Form1_Load(object sender, EventArgs e) { Task.Factory.StartNew(() => { if (Settings.CurrentSettings.EnableA) WeightReadingThreadA(); }); } private void WeightReadingThreadA() { SerialPort portA = new SerialPort(); TimeOutA(); timeOutWatchA.Start(); try { portA.Open(); if (portA.IsOpen) { while (isRunning) { //Does something here this.Invoke(new Action(() => { try { //display results to UI } catch (Exception) { } })); timeOutWatchA.Reset(); timeOutWatchA.Start(); } } } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void TimeOutA() { Task.Factory.StartNew(() => { while (isRunning) { Thread.Sleep(1000); if ((timeOutWatchA.ElapsedMilliseconds / 1000) > 3) { this.Invoke(new Action(() => { try { //display message to UI //This is where Iam getting //the error when I try to //close the form } catch (Exception) { } })); } } }); } private void BtnClose_Click(object sender, EventArgs e) { isRunning = false; this.Close(); }When I try and close the form I get the error "'Invoke or BeginInvoke cannot be called on a control until the window handle has been created". My question is how can i stop this error so i can close the form nicely. I have tried setting the variable isRunning to false before I close the form but this is not workingIf you think it you can achieve it 解决方案 这篇关于停止运行和关闭表单的任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 09-01 17:01