Implement Timeout for function C#

二次信任 提交于 2020-01-25 18:35:27

问题


I develop some USB communication which custom made device. I have use this USB dll to made things easier:

HidLibrary

Very good library but have one little bug. For example if I send something to USB device and device doesnt responde to that (it is not right command, etc.) this dll toolbox waiting for command response to infinity!

Now I like to add some timeout if after some second it no response go further.

I use now method whith bool status response, that I know if reading was successful or not.

var readreport = _choosendevice.ReadReport();

Later I need "readreport" variable, because there inside (readreport.Data) are acceptet data.

My question is how to implement this line into some timeout command? I found already solution for bug, but was not working for me (bug fix link).

If any question please ask. If question is not questioned in the right way, sorry for that because I am beginner in C#. THANKS! for help


回答1:


You can use Tasks to do so:

Task<HideReport> myTask = Task.Factory.StartNew(() => _choosendevice.ReadReport(););
myTask.Wait(100); //Wait for 100 ms.

if (myTask.IsCompleted)
    Console.WriteLine("myTask completed.");
else
    Console.WriteLine("Timed out before myTask completed.");

HidReport report = myTask.Result;

EDIT I didn't know the return value of your function. It returns a HidReport objtect. I just modified the Task creation to fit the return type

As said in comments the library already provides this mechanism so you just can call the right method

HidReport report = await ReadReportAsync(timeout);

** EDIT ** This code gone well for me

HidDevice device = HidDevices.Enumerate().ToList().First(e =>e.Description.Contains("mouse"));

Task<HidReport> t = Task.Factory.StartNew(() => device.ReadReport(1000));

t.Wait();

HidReport report = t.Result;



回答2:


Late response, but in case someone visits this question:

It's better to use separate tasks for the result and the waiting.

var waitTask = Task.Delay(timeoutInMs);
Task<MyReport> reportTask = Task.Factory.StartNew(() => _choosendevice.ReadReport(););            
await Task.WhenAny(waitTask, reportTask );
if (reportTask.IsCompleted)
{
  return await reportTask;
}
else
{
  // preferred timeout error handling...
}

That way you do not have to wait for the timeout if the report is ready in time. (And Taks.Delay is better than Task.Wait because it doesn't block)




回答3:


Task<HidReport> myTask = Task.Factory.StartNew(() => _choosendevice.ReadReport());
myTask.Wait(1000);

if (myTask.IsCompleted)
{
     HidReport report = myTask.Result;
}
else
{
     myTask.Dispose();
     // show ERROR
}

Maybe this will work. Until now was working, just make few tests and then I confirm (I helped with this page this:))



来源:https://stackoverflow.com/questions/31944324/implement-timeout-for-function-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!