私はこのようになりますクラスに取り組んでいます:一致が見つかったときイベントをクロススレッドで呼び出す?
public class MatchmakingService {
private bool working;
private List<MatchmakingUser> matchmakingUsers;
// ...
public MatchmakingService()
{
matchmakingUsers = new List<MatchmakingUser>();
}
public void StartService() {
var thread = new Thread(this.MatchmakingWork);
working = true;
thread.Start();
}
void MatchmakingWork() {
while (working)
{
// some work, match found!
{
if(onMatchFound != null)
onMatchFound(this, new NewMatchEventArgs(matchmakingUsers[i], matchmakingUsers[j]);
}
Thread.Sleep(1000);
}
}
}
通常、私はちょうどonMatchFoundイベントを起動したいと毎日それを呼び出すが、サービスのスレッドがあるので、このイベントのサブスクライバは別のスレッドになります - それをどう対処するのですか?私はそれをするのは安全ではないと、それが本当であれば私の選択肢は何かを読んだことがありますか?
注:私はWinFormsで作業していないので、ControlのInvoke Shenanigansはありません。
これは状況によって異なります。イベントのサブスクライバが別のスレッドにあるときは、それだけで何も問題はありません(特に、UIプラットフォームになく、UIスレッドに何もディスパッチする必要がない場合)。 – Evk