BenjaminRamsay | 2017-01-27 21:38:01 UTC | #1
I'm doing a simple WinForms app that listens for notifications using the C# SDK NotificationHandler. When certain notifications are received, I pop up a form with some info. The new form that I Show() is unresponsive and it's controls are not fully drawn, like the UI thread is being blocked. The original form is fine. Using ShowDialog() works fine, but doesn't fit my needs.
I will dig into NotificationHandler and websocket-sharp more to try to find out why, but I thought I'd float it here to see if anyone has an idea off the top of their head.
Simple test code to replicate the behavior:
var handler = new NotificationHandler(); handler.AddSubscription($"v2.users.{_me.Id}.presence", typeof(UserPresenceNotification)); handler.NotificationReceived += (data) => { if (data.GetType() == typeof(NotificationData<UserPresenceNotification>)) { var presence = (NotificationData<UserPresenceNotification>)data; Console.WriteLine($"New presence: {presence.EventBody.PresenceDefinition.SystemPresence}");
var testForm = new TestForm(); testForm.Show(); // The form appears, but unresponsive. } };
KevinGlinski | 2017-01-30 14:38:34 UTC | #2
in .net, you need to do UI operations on the main UI thread so you can't create a new window on a background thread. The answer to this SO question should help
http://stackoverflow.com/questions/11995466/c-sharp-calling-form-show-from-another-thread
BenjaminRamsay | 2017-01-30 22:06:42 UTC | #3
Thanks, makes sense that we'd be in a background thread in this event handler. Adjusting my test code as follows does the trick:
Declare a global form reference: private Form mainFormRef;
In the constructor or original form Load: mainFormRef = this;
In the NotificationReceived event handler: var testForm = new TestForm(); mainFormRef.Invoke((MethodInvoker)(() => { ` testForm.Show();` }));
system | 2017-08-28 19:31:39 UTC | #4
This post was migrated from the old Developer Forum.
ref: 857