我注意到当您创建Web服务对象(继承自SoapHttpClientProtocol)并使用Async方法时,它会在Windows GUI线程上进行回调。

  1. 有谁知道这是如何运作的?
  2. 我怎样才能达到同样的目的。
  3. 我认为这样可以节省我在GUI表单中检查InvokeRequired的情况,如果我确定回调总是在gui线程上发生。

有帮助吗?

解决方案

我怀疑它使用 AsyncOperationmanager.SynchronizationContext 静态获取同步上下文。然后,这允许您适当地发布回调。

其他提示

辉煌。谢谢你的回答。这两种选择似乎都有效并且有其优势。

以下是我用来测试的示例代码:

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

您可以在主线程中创建一个WindowsFormsSynchronizationContext对象,然后在另一个线程上调用其Send方法。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top