【发布时间】:2015-12-30 09:37:47
【问题描述】:
我有一个引发多个事件的服务,其中一些可以同时引发。我需要处理这些事件并根据事件参数运行可能需要长时间运行的方法。
我所做的是创建一个BlockingCollection<T>,它将事件存储在一个Task 中,它将继续一次处理一个事件,直到收到停止使用CancellationTokenSource 的信号。
我担心的是我没有很好地处理同步。
这是处理所有事情的类(它被用作WPF ViewModel):
public class EventsTest
{
//private fields
private BlockingCollection<IoEventArgs> _queue;
private CancellationTokenSource _tokenSource;
private IoService _ioService;
private Task _workerTask;
private static EventWaitHandle _eventWaiter;
public EventsTest()
{
_queue = new BlockingCollection<IoEventArgs>();
_tokenSource = new CancellationTokenSource();
_eventWaiter = new EventWaitHandle(false, EventResetMode.AutoReset);
//this is the object that raises multiple events
_ioService = new IoService();
_ioService.IoEvent += _ioService_IoEvent;
//Start Listening
var t = Task.Factory.StartNew(StartListening, _tokenSource, TaskCreationOptions.LongRunning);
}
//IO events listener
private void _ioService_IoEvent(string desc, int portNum)
{
//add events to a blocking collection
_queue.Add(new IoEventArgs() { Description = desc, PortNum = portNum });
}
private void StartListening(object dummy)
{
//process the events one at a time
while (!_tokenSource.IsCancellationRequested)
{
var eve = _queue.Take();
switch (eve.PortNum)
{
case 0:
LongRunningMethod(eve.Description);
break;
case 1:
//invoke a long running method
break;
default:
break;
}
}
}
//sample long running method
private void LongRunningMethod(string data)
{
_eventWaiter.WaitOne(10000);
}
}
我怎样才能使这个过程在线程安全方面更加健壮?
在每个方法实现周围添加lock 会提高过程的安全性吗?
【问题讨论】:
标签: c# wpf multithreading events .net-4.6