I'm currently building an app that relies on DataGridView to receive updates via WAMP protocol, which involves working with new message events. My event handler looks like this:
private async void NewMessage(object sender, MessageEventArgs e)
{
await Task.Factory.StartNew(() => DataHolder.TableSource.Add(new
CustomData(e.Name, e.Surname,
e.Whatever, e.WhoTheHellCares)));
}
When such an event occurs, an exception is thrown: System.InvalidOperationException
"An attempt to access control element which was created in a different thread".
DataHolder
is a static class that exists within same namespace with the form class that has this event handler, DataHolder.TableSource
is a BindingList<T>
which is bound in Form.Load
event to the DataGridView
control created in Form1.Designer.cs .
I've read an answer to a related issue here, that mentioned await
being able to automatically marshall something to UI thread if needed, but my wild and incompetent guess is that await
does not recognize a databinding, so it must be told explicitly to do so, how though?
I need a .net 4.5 solution here or proof that tasks and awaits are unable to solve my problem. But I think they are more than able. Just that I have trouble to apply it to my own situation here.
UPDATE
Wow, what the hell.. Even when my handler looks like this, it still gives me the same exception.
private void NewMessage(object sender, MessageEventArgs e)
{
DataHolder.TableSource.Add(new
CustomData(e.Name, e.Surname,
e.Whatever, e.WhoTheHellCares));
}
I guess it has something to do with the class itself that is firing an event. Well.. I tried D:
UPDATE I've used debugging tools and here's the deal - the event itself is already nested in another thread. Will try to rewrite the source code for the library I'm using so that it will support progress reports. Wish me f`kin luck D: