При запуске метода с параметром делегатом в отдельном потоке виснет все приложение - C#
Формулировка задачи:
Листинг программы
- public partial class MainWindow : Window
- {
- public delegate void ServerStart(Server.Send t);
- public MainWindow()
- {
- Server test = new Server();
- Thread t = new Thread(test.Start);
- t.Start();
- }
- public void WriteMessage(string msg)
- {
- ChatBox.Items.Add(msg);
- }
- private void Send_Click(object sender, RoutedEventArgs e)
- {
- Server test = new Server();
- ServerStart start_delegate = new ServerStart(test.Start);
- IAsyncResult result = start_delegate.BeginInvoke(WriteMessage, null, null);
- start_delegate.EndInvoke(result);
- InitializeComponent();
- }
- }
- namespace Chat
- {
- public class Server
- {
- public delegate void Send(string msg);
- public void Start(Send test)
- {
- TcpListener listen = null;
- try
- {
- int port = 4000;
- IPAddress iaddress = IPAddress.Parse("127.0.0.1");
- listen = new TcpListener(iaddress, port);
- listen.Start();
- byte[] bytes = new byte[256];
- string data = null;
- while (true)
- {
- TcpClient client = listen.AcceptTcpClient();
- NetworkStream stream = client.GetStream();
- int i;
- while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
- {
- data = Encoding.Unicode.GetString(bytes, 0, i);
- test(data);
- data = data.ToUpper();
- byte[] msg = Encoding.Unicode.GetBytes(data);
- stream.Write(msg, 0, msg.Length);
- }
- client.Close();
- }
- }
- catch
- {
- }
- finally
- {
- listen.Stop();
- }
- }
- public void Start()
- {
- TcpListener listen = null;
- try
- {
- int port = 4000;
- IPAddress iaddress = IPAddress.Parse("127.0.0.1");
- listen = new TcpListener(iaddress, port);
- listen.Start();
- byte[] bytes = new byte[256];
- string data = null;
- while (true)
- {
- TcpClient client = listen.AcceptTcpClient();
- NetworkStream stream = client.GetStream();
- int i;
- while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
- {
- data = Encoding.Unicode.GetString(bytes, 0, i);
- //test(data);
- data = data.ToUpper();
- byte[] msg = Encoding.Unicode.GetBytes(data);
- stream.Write(msg, 0, msg.Length);
- }
- client.Close();
- }
- }
- catch
- {
- }
- finally
- {
- listen.Stop();
- }
- }
- }
- }
Решение задачи: «При запуске метода с параметром делегатом в отдельном потоке виснет все приложение»
textual
Листинг программы
- Server test = new Server();
- ServerStart start_delegate = new ServerStart(test.Start);
- IAsyncResult result = start_delegate.BeginInvoke(WriteMessage, null, null);
- start_delegate.EndInvoke(result);
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д