访问其他线程的异步网络问题. [英] Async networking problem with accessing other threads.

查看:110
本文介绍了访问其他线程的异步网络问题.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经注释了引起错误的行,因为正在访问其他线程.我如何正确访问此信息?

I've commented the line that causes error, because other thread is getting accessed. How do i access this information correctly?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Chat
{
    public partial class Form1 : Form
    {
        Socket clientSocket;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {


        }

        private void hostButton_Click(object sender, EventArgs e)
        {
            Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            serverSocket.Bind(new IPEndPoint(IPAddress.Any, 43742));
            serverSocket.Listen(5);

            serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), serverSocket);
        }

        private void AcceptCallback(IAsyncResult ar)
        {
            Socket serverSocket = (Socket)ar.AsyncState;
            Socket clientSocket = serverSocket.EndAccept(ar);

            StateObject state = new StateObject(clientSocket);

            clientSocket.BeginReceive(state.buffer, 0, state.buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), state);

        }

        private void ReceiveCallback(IAsyncResult ar)
        {
            StateObject state = (StateObject)ar.AsyncState;
            Socket clientSocket = state.workSocket;

            int bytesReceived = clientSocket.EndReceive(ar);

            string message = Encoding.ASCII.GetString(state.buffer);

            chatTextBox.Text = message; // This line is causing error as server receives message. How do I do it correctly? How can i set this textbox to received message text?

            clientSocket.BeginReceive(state.buffer, 0, state.buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), state);

        }

        private void connectButton_Click(object sender, EventArgs e)
        {
            clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            clientSocket.BeginConnect(new IPEndPoint(IPAddress.Parse("192.168.1.72"), 43742), new AsyncCallback(ConnectCallback), clientSocket);
        }

        private void ConnectCallback(IAsyncResult ar)
        {
            Socket clientScoket = (Socket)ar.AsyncState;
            clientScoket.EndConnect(ar);
        }

        private void sendMessage_Click(object sender, EventArgs e)
        {
            SendMessageToSocket(clientSocket, "yolo");
        }

        private void SendMessageToSocket(Socket socket, string message)
        {
            StateObject state = new StateObject(socket);

            state.buffer = Encoding.ASCII.GetBytes(message);

            socket.BeginSend(state.buffer, 0, state.buffer.Length, SocketFlags.None, new AsyncCallback(SendCallback), state);
        }

        private void SendCallback(IAsyncResult ar)
        {
            StateObject state = (StateObject)ar.AsyncState;
            Socket handler = state.workSocket;

            int sentBytes = handler.EndSend(ar);

        }
    }
}

StateObject:

StateObject:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace Chat
{
    internal class StateObject
    {
        internal StateObject(Socket socket)
        {
            workSocket = socket;
        }

        public static readonly int BufferSize = 1024;

        public byte[] buffer = new byte[1024];

        public Socket workSocket;

    }
}

推荐答案

您将需要将执行转移到创建用户界面的线程上.这可以通过调用任何控件的方法来实现,包括表单本身.例如,您可以这样操作:

You will need to transfer execution to the thread that created the User Interface. This can be done by means of the method Invoke of any control, including the form itself. For instance, you can do it like this:

this.Invoke(new MethodInvoker(
    () => chatTextBox.Text = message;
)); 


这篇关于访问其他线程的异步网络问题.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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