【问题标题】:WPF Socket client structuringWPF Socket客户端结构
【发布时间】:2018-08-19 15:33:51
【问题描述】:

我的问题可能看起来有点奇怪,但是使用 MVVM 模式创建 WPF Socket 客户端的最佳方法是什么。

现在在我的 ViewModel 上,我创建了一个线程,它尝试在 while 循环中连接到服务器,并等待连接,连接后它会从服务器获取数据。

有没有更好的方法可以让我在不阻塞主 UI 线程的情况下不必使用新线程?

相关ViewModel代码:

    serverInfo.ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serverInfo.PORT = 1488;
//Initialize LeecherList
p_LeecherList = new ObservableCollection<LeecherDetails>();
//Subscribe to CollectionChanged Event
p_LeecherList.CollectionChanged += OnLeecherListchanged;

AccountsInfo = JsonConvert.DeserializeObject<RootObject>(File.ReadAllText(Path.Combine(Directory.GetCurrentDirectory(), "Accounts.json")));
foreach (var x in AccountsInfo.Accounts)
{
    p_LeecherList.Add(new LeecherDetails("N/A", x.Email, x.Password, false, "Collapsed"));
}

base.RaisePropertyChangedEvent("LeecherList");

Thread ConnectionLoop = new Thread(() =>
{
    ServerStatus = "Connecting...";
    while (true)
    {
        if (!serverInfo.HasConnectedOnce && !serverInfo.ClientSocket.Connected)
        {
            try
            {
                serverInfo.ClientSocket.Connect(IPAddress.Loopback, serverInfo.PORT);
            }
            catch (SocketException)
            {
            }
        }
        else if (serverInfo.ClientSocket.Connected && !serverInfo.HasConnectedOnce)
        {
            serverInfo.HasConnectedOnce = true;
            ServerStatus = "Online";
            break;
        }
    }
    while (true)
    {
        try
        {
            var buffer = new byte[8000];
            int received = serverInfo.ClientSocket.Receive(buffer, SocketFlags.None);
            if (received == 0) return;
            var data = new byte[received];
            Array.Copy(buffer, data, received);
            var st = helper.ByteToObject(data);
            if (st is string info)
            {
            }
            else
            {

            }
        }
        catch
        {
            continue;
        }
    }
});
ConnectionLoop.IsBackground = true;
ConnectionLoop.Start();

提前致谢。

【问题讨论】:

    标签: c# wpf sockets mvvm


    【解决方案1】:

    现在在我的 ViewModel 上,我创建了一个线程,它尝试在 while 循环中连接到服务器,并等待连接,连接后它会从服务器获取数据。

    有没有更好的方法可以让我不必使用新线程而不阻塞主 UI 线程?

    好吧;你应该把这个逻辑放在Service 中。

    示例:


    所以,你可以像这样创建一个服务,注意:开始、停止和传递数据的事件。

    基本思想是将更多类似业务的通信逻辑移动到一个单独的服务中,这样,如果您以后需要更改它,逻辑就会更加孤立,并且不会与您的视图模型混合。

    //note, you could encapsulate functionality in an interface, e.g.: IService
    public class SomeService 
    {
         public event EventHandler<YourEventData> OnSomethingHappening;
         public SomeService(some parameters)
         {
             //some init procedure
         }
    
         public void Stop()
         {
            //your stop logic
         }
    
         public void Start()
         {
            //your start logic
         }
    
         private void Runner() //this might run on a seperate thread
         {
             while(running)
             { 
                 if (somecondition)
                 {
                      OnSomethingHappening?.Invoke(this, new YourEventData());
                 }
             }
         }
    
         public string SomeFooPropertyToGetOrSetData {get;set;}
    }
    

    在您的应用程序的某处创建其中之一,可能在启动时。

    然后将它传递给您的视图模型,也许是通过构造函数。在这种情况下,您的视图模型将如下所示:

    public class YourViewModel
    {
         private SomeService_service;
         public YourViewModel(SomeServiceyourService)
         {
              _service = yourService;
              _service.OnSomethingHappening += (s,a) =>
              {
                  //event handling
              };
         }
    }
    
    //etc.
    

    【讨论】:

    • 将 ViewModel 传递给服务是否明智?比如命令的工作原理。
    • 不,通常你会将服务传递给视图模型......并通过事件更新视图模型中的值......“视图模型”正在“消耗”“服务”,而不是另一个一路走来。
    • 此外,正确执行此操作时,您的服务应该独立于视图模型。
    • 谢谢你,我会玩它,看看我能想出什么。
    • 欢迎您,祝您好运,让我知道。顺便说一句,感谢最好表达为赞成和/或标记为答案;-)
    猜你喜欢
    • 1970-01-01
    • 2013-12-05
    • 1970-01-01
    • 2016-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-20
    • 1970-01-01
    相关资源
    最近更新 更多