Usamos cookies para medir audiência e melhorar sua experiência. Você pode aceitar ou recusar a qualquer momento. Veja sobre o iMasters.
Pessoal,Alguém poderia me ajudar com o erro abaixo? Estou colando o código do meu programa também. Dei uma pesquisada e vi que talvez eu possa solucionar isto usando a classe BackgroundWorker, mas não faço nem idéia de como fazer...Sugestões?ERRO: System.InvalidOperationException: Cross-thread operation not valid: 'inputTextBox' accessed from a thread other than the thread it was created on.++++++++++++++++++++++++++++++++++++++++++++++++++using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Net;using System.Net.Sockets;using System.IO;using System.Threading;namespace ServerApp{ public partial class ServerAppForm : Form { private Socket connection; private NetworkStream socketStream; private BinaryWriter writer; private BinaryReader reader; private Thread readThread; public ServerAppForm() { InitializeComponent(); // create a new thread from the server readThread = new Thread(new ThreadStart(RunServer) ); readThread.Start(); } public void RunServer() { TcpListener listener; // wait for a client connection try { // Step 1: create TcpListener int port = 5000; IPAddress localAddr = IPAddress.Parse("127.0.0.1"); listener = new TcpListener(localAddr, port); // Step 2: TcpListener waits for connection request listener.Start(); // Step 3: establish connection upon client request while (true) { inputTextBox.Enabled = true; sendButton.Enabled = true; // accept an incoming conection connection = listener.AcceptSocket(); // create NetworkStream object associated with socket socketStream = new NetworkStream(connection); // create objects for transferring data across stream writer = new BinaryWriter(socketStream); reader = new BinaryReader(socketStream); string theReply = ""; // inform client that connection was successfull writer.Write("SERVER>>> Connection successful"); displayTextBox.Text += reader.ReadString(); // Step 4: read String data sent from client do { try { // read the string sent to the server theReply = reader.ReadString(); displayTextBox.Text += "\r\n" + theReply; } // handle exception if error erading data catch ( Exception ) { break; } } while (connection.Connected ); displayTextBox.Text += "\r\nUser terminated connection.\r\n"; // Step 5: close connection writer.Close(); reader.Close(); socketStream.Close(); connection.Close(); } } // end try catch (Exception error) { MessageBox.Show(error.ToString()); } } private void ServerAppForm_FormClosing(object sender, FormClosingEventArgs e) { System.Environment.Exit(System.Environment.ExitCode); } private void sendButton_Click(object sender, EventArgs e) { writer.Write(inputTextBox.Text); displayTextBox.Text += "\r\n" + inputTextBox.Text; inputTextBox.Clear(); } }}
Carregando comentários...