Sending a message to the Windows GUI Thread
-
03-07-2019 - |
Question
I've noticed that when you create a web service object (inheriting from SoapHttpClientProtocol) and you use the Async method, it makes the callback on the Windows GUI thread.
- Does anyone know how this works?
- How can I achieve the same thing.
I figure this will save me having to check for InvokeRequired in my GUI forms if I am sure the callback is always occurring on the gui thread.
Solution
I suspect it uses AsyncOperationmanager.SynchronizationContext to statically get a synchronization context. This then allows you to post callbacks appropriately.
OTHER TIPS
Brilliant. Thanks for the answers. Both options seem to work and have their strengths.
Here's the sample code I used to test with:
public partial class AsyncTest : Form
{
static void Main()
{
Application.Run(new AsyncTest());
}
AsyncOperation _operation;
SynchronizationContext _context;
TextBox _textBox;
public AsyncTest()
{
_operation = AsyncOperationManager.CreateOperation(null);
_context = WindowsFormsSynchronizationContext.Current;
_textBox = new TextBox();
this.Controls.Add(_textBox);
new Thread(AsyncThread).Start();
}
void AsyncThread()
{
_operation.Post(GuiThread, null);
_context.Post(GuiThread, null);
}
void GuiThread(object state)
{
_textBox.Text = _textBox.InvokeRequired ? "Didn't work" : "It Worked";
}
}
You can create a WindowsFormsSynchronizationContext object in the main thread and then, on a different thread, call its Send method.