Click here to Skip to main content
15,881,600 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,
Lets say I have a sensor class manager (SensorServer).
Inside that class I have an event that helps me receive status changes regarding the sensor:
public event OnSensorStatus OnSensorStatusEvent;

In my view model (EventsMgr.cs), I create an instance of SensorServer and register for this event:
Server = new SensorServer();
Server.OnSensorStatusEvent += Srv_OnSensorStatusEvent;
Server.StartServer();

Whenever an event occurs, the code goes into the following method:
private void Srv_OnSensorStatusEvent(SensorStatus sensorStatus)
{
    //Here I want to call: 
	//var task = Server.GetSensorById(sensorStatus.Id);      
	//And when the task completed I want to call a callback method           
}

Inside the event, the SensorStatus contains an ID with which I can obtain the event-related sensor by calling the following asynchronous method inside SensorServer:
public async Task<Sensor> GetSensorById(Guid id)
{
await Task.Delay(_random.Next(_maxDelayForGetSensor));           
return _sensors.FirstOrDefault(sensor => sensor.Id == id);
}

My question is this:
The events happen every 200 milliseconds or so and I wanted to know what is the best way to operate it? My goal is to call GetSensorById every time the event happens (in a separate thread) and when a reply comes back access the callback with the response.
I need each call to be handled individually.
I cannot change anything inside the SensorServer.cs.

What I have tried:

.............................................
Posted
Updated 23-Nov-21 1:39am
v2

1 solution

C#
//add 'async' to the method declaration
private async void Srv_OnSensorStatusEvent(SensorStatus sensorStatus)
{
    //await for the asynchronous method to complete and unwrap the Task<Sensor>
    //that is returned from the 'Server.GetSensorById' method
	Sensor sensor= await Server.GetSensorById(sensorStatus.Id);      
	//enter code that uses the returned Sensor instance sensor       
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900