[英]c# Delegate Throws System.InvalidOperationException
I have a Thread that retrieves infos from an xml file. 我有一个从xml文件中检索信息的线程。 In my main form I have a checkbox that in case a boolean in the xml is true must be checked by the thread.
在我的主窗体中,我有一个复选框,以防xml中的布尔值为true,必须由线程检查。 I have created a Delegate but despite this when the thread tries to change the value of the checkbox a System.InvalidOperationException is thrown.
我创建了一个Delegate,但是当线程尝试更改复选框的值时,抛出System.InvalidOperationException。 Why ?!?
为什么?!?
private delegate void ProjectFileReloadDelegate(string pp);
private void ProjectFileReload(string projectPath)
{
if (this.InvokeRequired)
{
this.Invoke(new ProjectFileReloadDelegate(ProjectFileReload), projectPath);
}
else
{
//This throws the exception
//I retrive the anchorMode Info
anchorMode.Checked = ProjectOptions_v000.AnchorMode;
}
On one of my projects, which handled quite a few API, I used Task to handle async api calls. 在我的一个处理了相当多API的项目中,我使用Task来处理异步api调用。 Due to the uncertainty on weather it would be on Main GUI thread or another I used Task.Factory.StartNew with a TaskScheduler.FromCurrentSynchronizationContext() as parameter to handle any code updating the GUI.
由于天气的不确定性,它将在主GUI线程或另一个我使用Task.cheact.StartNew与TaskScheduler.FromCurrentSynchronizationContext()作为参数来处理任何更新GUI的代码。 The reference for this is from Microsoft the section titled "Specifying a synchronization context" The TaskScheduler.FromCurrentSynchronizationContext() tells it run on gui thread.
对此的引用来自Microsoft的标题为“指定同步上下文”的部分.TaskScheduler.FromCurrentSynchronizationContext()告诉它在gui线程上运行。
This is how I would update your code to prevent Exceptions from updating GUI content on other threads. 这是我更新代码以防止异常更新其他线程上的GUI内容的方法。
private delegate void ProjectFileReloadDelegate(string pp);
private void ProjectFileReload(string projectPath)
{
if (this.InvokeRequired)
{
this.Invoke(new ProjectFileReloadDelegate(ProjectFileReload), projectPath);
}
else
{
//This throws the exception
//I retrive the anchorMode Info
Task.Factory.StartNew(
delegate {
anchorMode.Checked = ProjectOptions_v000.AnchorMode;
}, TaskScheduler.FromCurrentSynchronizationContext()
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.