そもそも今回UIスレッドのことについて調べることになったのはdev-asp.net - このウェブサイトは販売用です! - dev-asp リソースおよび情報の通信ライブラリを使ってみた後輩と一緒にはまったから.
前にもはまったのに,今後も同じことで悩まないようにお勉強するのである.
コントロールを扱う処理はそのコントロールを持つフォームのスレッドから実行しなければならない.
そのため,その処理をMethodInvokerでラップして,フォームのInvoke()に渡して実行してもらうことになる.
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using PeerToPeerWorker; namespace UIThreadSample { public partial class Form1 : Form { P2PW p2p; ConnectTarget[] targets; public Form1() { InitializeComponent(); targets = new ConnectTarget[1]; targets[0] = new ConnectTarget("localhost", 22222); p2p = new P2PW(); p2p.OnPacketReceived += new PacketEventHandler(p2p_OnPacketReceived); //p2p.OnPeerConnected += new PeerEventHandler(p2p_OnPeerConnected); //p2p.OnPeerDisconnected += new PeerEventHandler(p2p_OnPeerDisconnected); //p2p.OnPeerListUpdated += new EventHandler(p2p_OnPeerListUpdated); } void p2p_OnPacketReceived(long from, byte[] data) { string s = Encoding.Unicode.GetString(data); // コントロールを操作する処理はすべてMethodInvokerでラップして MethodInvoker m = new MethodInvoker(delegate { this.checkBox1.Checked = !this.checkBox1.Checked; }); // 実行する this.Invoke(m); } private void button1_Click(object sender, EventArgs e) { p2p.Connect(targets); } } }