C#UDPクライアントのログ.txtファイルは、ボタンのクリックと別のスレッドのデータを使用しています
UDPを開始/停止し、.txtファイルに書き込むためのボタンコントロールを備えたUDPリスナを持っていますが、後者はうまく動作しません。
beginInvokeは[button_start_writing_Click]スレッドに 'data'を送信して、ボタンをクリックしたときではなく、自分自身をトリガーします。
データがテキストボックスで継続的に受信されるようにしたら、txtファイルへのログ記録を開始する瞬間を選択するのはどうでしょう?
事前に感謝します。
public partial class Form1 : Form
{
private UdpClient Client;
public Form1()
{
InitializeComponent();
}
private void button_start_Click(object sender, EventArgs e)
{
Client = new UdpClient(Convert.ToInt32(textBox_port.Text));
Client.BeginReceive(DataReceived, null);
button_stop.Click += Button_stop_Click;
}
private void DataReceived(IAsyncResult ar)
{
IPEndPoint ip = new IPEndPoint(IPAddress.Any, Convert.ToInt32(textBox_port.Text));
byte[] data;
try
{
data = Client.EndReceive(ar, ref ip);
if (data.Length == 0)
return; // No more to receive
Client.BeginReceive(DataReceived, null);
}
catch //(ObjectDisposedException)
{
return; // Connection closed
}
// Send the data to the UI thread
this.BeginInvoke((Action<IPEndPoint, string>)DataReceivedUI, ip, Encoding.UTF8.GetString(data));
// Send the data to the writer thread
this.BeginInvoke((Action<IPEndPoint, string>)button_start_writing_Click, ip, Encoding.UTF8.GetString(data));
private void button_start_writing_Click(object sender, EventArgs e)
{
string logfilePath = "C:\\Users\\I4T\\Desktop\\Test Output\\";
File.AppendAllText(logfilePath + "logtest.txt", "[" + DateTime.Now.ToString("dd-MM-yyyy hh:mm:ss.fff") + "] " + data);
}
何を望むかの詳細を見つける必要があり、あなたはそのが働いていない理由を確認するために追跡することができるはずです。あなたは何が間違っているのかを定義していません。あなたの「書き始め」は定義されていない "データ"をダンプするだけで、このコードは明らかにコンパイルできません。 – BugFinder
申し訳ありません。 button_start_writing_ BeginInvokeをクリックします。おそらく、私がそれに近づいている方法は最高ではありません。私はbutton_start_writing_Clickスレッドにデータを(beginInvokeを使用して)ダンプしています。しかし、残念なことに、残念ながら、トップスレッドのbeginInvokeは、 'Start Writing'ボタンをクリックするのではなく、txtファイルスレッドへの書き込みをトリガーしています。これを達成するためのよりよい方法の提案はありますか? – Jon
あなたが言ったので - これまでのところ単純なロジック/デザインの問題以上のものはありません – BugFinder