C# 如何在C中运行相同的后台工作程序并将其停止在循环中#
我执行了一个循环10次的遗传算法,每次我调用“FitnessFunction”函数时,我都会使用后台工作程序在拓扑上移动一个对象,一旦它到达一个特定点,我就会取消后台工作程序并返回到“genetic_algorithm”函数 不幸的是,我得到了以下错误:C# 如何在C中运行相同的后台工作程序并将其停止在循环中#,c#,backgroundworker,cross-thread,C#,Backgroundworker,Cross Thread,我执行了一个循环10次的遗传算法,每次我调用“FitnessFunction”函数时,我都会使用后台工作程序在拓扑上移动一个对象,一旦它到达一个特定点,我就会取消后台工作程序并返回到“genetic_algorithm”函数 不幸的是,我得到了以下错误: Cross-thread operation not valid: Control 'topology' accessed from a thread other than the thread it was created on... 我尝
Cross-thread operation not valid: Control 'topology' accessed from a thread other than the thread it was created on...
我尝试过的:
每次调用“FitnessFunction”函数时运行后台工作程序,该函数负责在特定条件下停止后台工作程序。WinForms禁止从主UI以外的线程访问控件 使用表单的
Invoke(…)
方法或使用SynchronizationContext
类
private SynchronizationContext context;
MyForm()
{
InitializeComponents();
context = SynchronizationContext.Current;
}
///// somewhere in another thread
context.Post(myCallbackInUIThread, null) // you can use Send for synchronous call
如何修复while(true),如何在那里使用invoke?您能完成回答吗?当您试图从非UI线程(worker)绘制控件时,会引发异常。请使用另一个方法包装绘制操作,并通过invoke/Post调用它。您应该研究如何使用
ReportProgress()
函数,该函数在UI线程上引发一个事件,您可以在其中更新控件。否则,对UI控件的调用必须封送到创建它们的UI线程。@xxbbcc:您能给出一个答案吗?