在TCP套接字上接收数据后更新UI

时间:2014-02-12 19:45:38

标签: c# .net sockets compact-framework

我认为我甚至没有问过这个问题,但在这里。 我有一个.NET CF应用程序,显示信息的数据网格。此应用程序通过TCP套接字连接到将定期广播数据的中央服务器。

如何在我的ShellForm上获取数据网格以进行更新。感觉错误的是在我的DAL中引用了我的ShellForm,其中发生了Socket的事情。

我会使用委托还是异步回调?只是寻找一点指导。谢谢!

2 个答案:

答案 0 :(得分:2)

DAL只能publish an Event,然后GUI可以订阅它 引用(和依赖)将从GUI到DAL。

同时注意您的线程安全性。

答案 1 :(得分:2)

我建议您的用户界面根本不了解您的DAL。我要做的就是创建一个中间人"演示者"观察DAL然后可以通过事件,回调或其他任何方式通知UI的类。

我很可能会创建一个实现INotifyPropertyChanged的演示者类,它允许您直接观看事件或数据绑定到您用来填充网格的属性。演示者还可以处理UI上下文的编组,因此UI或DAL都不必担心它。

某种伪代码可能看起来像这样。请记住,我的代码中有各种基础设施位,所以这不太可能只是编译,但它应该让你了解我如何解决问题。

class PointPresenter : INotifyPropertyChanged
{
    private IDataService DAL { get; set; }

    protected Control EventInvoker { get; private set; }

    public PointPresenter()
    {
        // get your DAL reference however you'd like
        DAL = RootWorkItem.Services.Get<IDataService>();
        EventInvoker = new Control();
        // this is required to force the EE to actually create the 
        // control's Window handle
        var h = EventInvoker.Handle;
    }

    protected void RaisePropertyChanged(string propertyName)
    {
        try
        {
            if (m_disposed) return;

            EventInvoker.BeginInvokeIfRequired(t =>
            {
                try
                {
                    PropertyChanged.Fire(this, propertyName);

                }
                catch (Exception e)
                {
                    Debug.WriteLine(e);
                }
            });
        }
        catch (ObjectDisposedException)
        {
            // if the Form to which we're sending a message is disposed, 
            // this gets thrown but can safely be ignored
        }
        catch (Exception ex)
        {
            // TODO: log this
        }
    }

    public int MyDataValue
    {
        get { return DAL.Data; }
        set
        {
            if (value == MyDataValue) return;
            DAL.Data = value;
            RaisePropertyChanged("MyDataValue");
        }
    }
}