为函数 C# 实现超时 [英] Implement Timeout for function C#

查看:52
本文介绍了为函数 C# 实现超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发了一些定制设备的 USB 通信.我使用这个 USB dll 使事情变得更容易:

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

HidLibrary

非常好的库,但有一个小错误.例如,如果我向 USB 设备发送了一些东西并且设备没有响应(它是不正确的命令等),这个 dll 工具箱正在等待对无穷大的命令响应!

现在我想添加一些超时,如果几秒钟后它没有进一步响应.

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

我现在使用带有 bool 状态响应的方法,我知道读取是否成功.

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

var readreport = _choosendevice.ReadReport();

稍后我需要readreport"变量,因为里面(readreport.Data)是接受数据.

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).

如有任何问题请追问.如果问题没有以正确的方式提问,抱歉,因为我是 C# 的初学者.谢谢!寻求帮助

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

推荐答案

您可以使用 Tasks 来做到这一点:

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 我不知道你的函数的返回值.它返回一个 HidReport 对象.我只是修改了任务创建以适应返回类型

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 ** 这段代码很适合我

** 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;

这篇关于为函数 C# 实现超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆