我正在上一个看起来像这样的课:
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恶作剧。
最简单的方法是创建队列。有多种实现队列的方法。我会在MatchmakingService
使用队列存储匹配项,其他线程必须调用该RaiseEvents()
方法来处理队列。这意味着,另一个线程应该有一个Timer / DispatcherTimer /,同时有睡眠等。
例子:
public class MatchmakingService
{
private bool working;
private List<MatchmakingUser> matchmakingUsers;
// ...
// the queue
private List<NewMatchEventArgs> _queue = new List<NewMatchEventArgs>();
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!
{
lock (_queue)
_queue.Add(new NewMatchEventArgs(matchmakingUsers[1], matchmakingUsers[2]));
}
Thread.Sleep(1000);
}
}
public void RaiseEvents()
{
NewMatchEventArgs[] copyOfQueue;
// create a copy (bulk action)
lock (_queue)
{
copyOfQueue = _queue.ToArray();
_queue.Clear();
}
// handle the items
if (onMatchFound != null)
foreach (var item in copyOfQueue)
onMatchFound(this, item); // indices are examples
}
public event EventHandler<NewMatchEventArgs> onMatchFound;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句