我有一个关于Visual Studio 2010 C sharp中的延迟的问题。 我需要时间延迟在程序中发送位置到伺服。现在我正在使用System.Threading.Thread.Sleep(200))但我需要延迟,我可以interupt。延迟程序就像睡觉()
当我使用睡眠时,该程序在睡眠过程中不起作用。 (点击按钮,轨迹栏移动...),但我必须在延迟期间控制程序。
什么是存在于VS像功能睡眠?
非常感谢您的回复。
马丁
我有一个关于Visual Studio 2010 C sharp中的延迟的问题。 我需要时间延迟在程序中发送位置到伺服。现在我正在使用System.Threading.Thread.Sleep(200))但我需要延迟,我可以interupt。延迟程序就像睡觉()
当我使用睡眠时,该程序在睡眠过程中不起作用。 (点击按钮,轨迹栏移动...),但我必须在延迟期间控制程序。
什么是存在于VS像功能睡眠?
非常感谢您的回复。
马丁
您可以使用Task.Delay
:
https://msdn.microsoft.com/en-us/library/hh194845(v=vs.110).aspx
public void mainFunction() {
//do stuff here
var delayTime = 1.5;
CancellationTokenSource source = new CancellationTokenSource();
var t = Task.Run(async delegate
{
await Task.Delay(TimeSpan.FromSeconds(delayTime), source.Token);
delayableFunction();
});
//can cancel here if necessary
source.Cancel();
//just continue on with other stuff...
}
public void delayableFunction() {
//do delay-able stuff here
}
想想你可能会混合使用几种语言哈哈。在C#中没有'function'关键字 –
感谢您指出这一点,我正在使用Javascript#。 –
使用带有消除令牌
这里有一个简单的例子异步Task.Delay()
功能:
bool sendPos = true;
public async Task SomeFunction(CancellationToken token)
{
while (sendPos)
{
SendServoPos();
await Task.Delay(1000, token)
}
}
public void MainFunction()
{
var tokenSource = new CancellationTokenSource();
// Fire and Forget - Note it will silently throw exceptions
SomeFunction(tokenSource.Token)
// Cancel Loop
sendPos = false;
tokenSource.Cancel();
}
你可以工作的过程中异步任务,而不阻止您的应用程序..因为你正在使用VS2010使用Task.Delay()(它唯一的块当前任务)
public async Task SomeWork()
{
while (someCondition)
{
//do some work
await Task.Delay(100);//milliseconds
}
}
,你不会有权访问C#5功能(异步/正在等待关键字),并且很可能仅限于.NET 4.0。不幸的是,该版本没有Task.Delay方法。
如果是这种情况,最简单的选择可能使用System.Threading.Timer或System.Timers.Timer根据您的需要。两者都会在延迟后在线程池线程上执行一个方法。您可以在打勾前停止他们两人,并且他们都支持“无限”期间。
停止线程计时器不明显,使用Timer.Change方法。
上面的链接有很好的使用示例。
当你说“VS中存在什么......”时,你的确是这样认为的:“Visual Studio中只存在IDE而不是语言。” –
是的,很抱歉,谢谢你的修理。 –