I have a Thread that retrieves infos from an xml file. In my main form I have a checkbox that in case a boolean in the xml is true must be checked by the thread. I have created a Delegate but despite this when the thread tries to change the value of the checkbox a System.InvalidOperationException is thrown. 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. 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. The reference for this is from Microsoft the section titled "Specifying a synchronization context" The TaskScheduler.FromCurrentSynchronizationContext() tells it run on gui thread.
This is how I would update your code to prevent Exceptions from updating GUI content on other threads.
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()
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.