Usman Mehmood
Usman Mehmood

Reputation: 194

.NET Execute a method for fixed 5 seconds and then stop

I want to read data on serial port using SerialPort.ReadLine() for exactly 5 seconds, and then stop reading. Currently I am using this code:

Task t = Task.Run(() => { ReadSerial(); });    // this is the function that reads from serial port
TimeSpan ts = TimeSpan.FromMilliseconds(5000); // I set the timeout period here. Like 5 seconds

if (!t.Wait(ts))                               // After 5 seconds, this runs
{
    port.Close();
    WriteToFile();
    t.Dispose();
}

Now, when executed once, it works perfectly fine. But if I execute it again in the same program, it never leaves the Task t = Task.Run(() => { ReadSerial(); }); line.

So I am wondering if this is a good approach to do what I am trying to do, and what am I doing wrong here? Or if there is a better approach?

Upvotes: 0

Views: 335

Answers (1)

Ken Brittain
Ken Brittain

Reputation: 2265

The docs state the By default, the ReadLine method will block until a line is received. My guess is that the first time you are reading all of the data or a newline is never received. The blocking call never returns so you are stuck.

Try setting the ReadTimeout and handling the exception rather than attempting your own timeout.

https://learn.microsoft.com/en-us/dotnet/api/system.io.ports.serialport.readline?view=dotnet-plat-ext-6.0

Upvotes: 1

Related Questions