[你好,我是一名学生,我还不习惯c#。我正在用服务器和客户机编写程序,它们通过套接字连接。我正在尝试使用while循环实现一种在数据可用时从流中读取的方法。如果在读取/写入流之前使用MessageBox.Show()显示消息,则可以避免崩溃。我不知道为什么没有显示消息的程序不起作用...
来自客户端线程的部分代码:
byte[] message = new byte[1024];
message = Encoding.UTF8.GetBytes("hello");
dataStream.Write(message, 0, message.Length);
message = new byte[1024];
MessageBox.Show(""); //WITHOUT THIS MESSAGEBOX MESSAGE PROGRAM FREEZES
while (true)
{
if (dataStream.DataAvailable)
{
dataStream.Read(message, 0, message.Length);
break;
}
}
receivedMessage = Encoding.UTF8.GetString(message);
textBox4.Invoke(new Action(() => textBox4.AppendText(Environment.NewLine + "Message: " + receivedMessage)));
服务器代码的一部分:
byte[] message = new byte[1024];
if(dataStream.DataAvailable)
dataStream.Read(message, 0, message.Length);
receivedMessage = Encoding.UTF8.GetString(message);
textBox4.Invoke(new Action(() => textBox4.AppendText(Environment.NewLine + "MessageH: " + receivedMessage)));
message = new byte[1024];
message = Encoding.UTF8.GetBytes("Second message!");
dataStream.Write(message, 0, message.Length);
现在主要是猜测,因为我们几乎没有足够的代码可以肯定地说什么:
JiT编译器呢?
目的之一是死代码检测。它削减了它预计不会产生影响的代码。不幸的是,它仍然只是一个计算机程序,因此会发生误报。例如,尝试对x32 Framework安装强制实施OOM异常,我不得不竭尽所能地not将代码由JiT剪切掉:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OOM_32_forced
{
class Program
{
static void Main(string[] args)
{
//each short is 2 byte big, Int32.MaxValue is 2^31.
//So this will require a bit above 2^32 byte, or 2 GiB
short[] Array = new short[Int32.MaxValue];
/*need to actually access that array
Otherwise JIT compiler and optimisations will just skip
the array definition and creation */
foreach (short value in Array)
Console.WriteLine(value);
}
}
}
MessageBox将阻止将整个函数切为死代码。向用户输出一些东西被假定为“具有效果”。但是,它的其他部分仍然有资格进行死代码检测。
不幸的是,您没有提供给我们最小的,完整的可验证示例。因此,我们真的无法帮助您进一步解决。