I have a Device interface:
public interface IDevice
{
double Measure();
}
Some classes that implement that interface have a measuring instrument:
public class InstrumentedDevice : IDevice
{
public MeasuringInstrument Instrument { get; set; }
public double Measure()
{
if (Instrument != null)
return Instrument.DoMeasuring();
return 0;
}
}
I’d like to group the instances of InstrumentedDevice according to their Instrument property so that the result is a collection of groups in which each device uses the same instrument as all the other devices in its group.
I’d then like to start a new thread for each group and perform the measuring in parallel.
That would look something like this:
public void MeasureAllDevices(IEnumerable<InstrumentedDevice> devices)
{
var groups = devices.GroupBy(d => d.Instrument);
foreach (var gr in groups)
{
var bgw = new BackgroundWorker();
bgw.DoWork += (s, e) =>
{
foreach (var device in gr)
{
device.Measure();
}
};
bgw.RunWorkerAsync();
}
}
The problem is that I don’t get a collection of InstrumentedDevice as the parameter for MeasureAllDevices. I get a collection of IDevice:
public void MeasureAllDevices(IEnumerable<IDevice> devices)
{
}
My question is this: Is there a pattern I can follow to solve my problem? Not all devices will have a MeasuringInstrument, and some devices may have different means of determining whether or not they can be measured in parallel.
I’d like to add something to the IDevice interface like CanBeMultiThreadedWith(IDevice other), but I’m not sure how that would work.
1 Answer