views:

663

answers:

3

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.

  1. Does anyone know how this works?
  2. 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.

+3  A: 

I suspect it uses AsyncOperationmanager.SynchronizationContext to statically get a synchronization context. This then allows you to post callbacks appropriately.

Jon Skeet
+1  A: 

You can create a WindowsFormsSynchronizationContext object in the main thread and then, on a different thread, call its Send method.

Stefan Schultze
+2  A: 

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";
        }
    }
Richard Nienaber