如何在Windows Forms应用程序中实现异步模式? [英] How to implement async pattern in windows forms application?

查看:97
本文介绍了如何在Windows Forms应用程序中实现异步模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Winforms应用程序中使用了MVC模式.我需要异步调用远程服务.因此,在View中的某个事件上,我调用了相应的Presenter方法.在Presenter中,我调用服务的BeginInvoke方法.但是to View必须仅在主线程中更新.实际上,我可以将CallBack指向View中的某些函数,并更新其控件状态,但这与MVP模式冲突-View不能对其所携带的数据负责.此回调函数必须在Presenter中.但是如何在主线程中调用View?

I'm using an MVC pattern in winforms application. I need to call remote service asynchronously. So On some event in View I invoke corresponding Presenter method. In Presenter I call BeginInvoke method of service. But to View must be updated only in Main Thread. I could actualy point CallBack to some function in View, and update it`s controls state, but this conflicts with MVP pattern - View must not be responsible for data it carries. This callback function must be in Presenter. But how then invoke View in Main Thread?

推荐答案

将回调函数放在演示者中.让演示者调用视图上需要的任何更新功能/让视图观察演示者的状态并处理完成"事件.在视图的功能中,如果视图是由Windows窗体实现的,请测试InvokeRequired属性以查看调用是否已在Windows线程上进行.如果还没有,请改用Invoke调用它.

Put the callback function in the presenter. Have the presenter call whatever update function on the view is required/have the view observe the presenter's state and handle the 'completed' event. In the view's function, if the view is implemented by a windows Form, test the InvokeRequired property to see if the call has come in on the windows thread. If it hasn't, then use Invoke to invoke it instead.

    private void SetMessage(string message)
    {
        if (InvokeRequired)
        {
            BeginInvoke(new Action(() => SetMessage(message)));
            return;
        }

        button1.Text = message;
    }

这篇关于如何在Windows Forms应用程序中实现异步模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆