I have a WinForms client with 2 forms. The first form calls a separate class uses 'SignalR' for notifications from a WebApi. The setup of the hub proxy for a particular message in the class is:
onResult = myProxy.On<int>("Result", (id) =>
{
Result?.Invoke(this, new ResultEventArgs(id));
});
In the first form I subscribe to the Result
event and then I have:
private void OnResult(object sender, ResultEventArgs e)
{
using (var form = new SecondForm(e))
{
var dialogResult = form.ShowDialog(this);
if (dialogResult == DialogResult.Cancel)
return;
}
}
I get a CrossThreadException
on var dialogResult = form.ShowDialog(this);
The first form ( this
) is opened on the UI thread. The second form is being opened in same thread as the SignalR
class uses.
I do need to open the second form using ShowDialog(this)
as I need it to be the topmost form in the app.
Is there a workaround for this problem? Is it possible to open the second form in the UI thread too?
UPDATE:
A workaround which works to do:
form.TopMost = true;
form.StartPosition = FormStartPosition.CenterScreen;
The only drawback is that the form is the topmost form on the desktop, not only within the application.
You can not create, change, or access any UI control on any thread other than the single UI thread. You must call .Invoke(...)
on an existing control to marshall calls from another thread back to the UI.
Try this:
private void OnResult(object sender, ResultEventArgs e)
{
Action x = () =>
{
using (var form = new SecondForm(e))
{
var dialogResult = form.ShowDialog(this);
if (dialogResult == DialogResult.Cancel)
return;
}
};
this.Invoke(x);
}
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.