我想做的是每10秒后暂停一次视频 视频应在10秒后暂停,直到视频结束
下面给出的代码给出了意想不到的结果 视频在第一时间暂停(即10秒后) 但是当我再次上场时它应该在10s后暂停,但在我的情况下,它有时会在8s,3s 5s等时间内随机停顿 我该怎么办?? 请帮忙 谢谢!
void PlayClick(object sender, EventArgs e)
{
VideoControl.Play();
var dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, 10);
dispatcherTimer.Start();
}
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
VideoControl.Pause();
}
答案 0 :(得分:1)
在dispatcherTimer_Tick-Method:
中添加此项dispatcherTimer.Stop();
将以下部分移动到构造函数中:
dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, 10);
将DispatcherTimer设为全局变量。
编辑:这应该是什么样子:
class MyClass
{
private DispatcherTimer _dispatcherTimer; //now your dispatcherTimer is accessible everywhere in this class
public MyClass()
{
_dispatcherTimer = new DispatcherTimer();
_dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
_dispatcherTimer.Interval = new TimeSpan(0, 0, 10);
}
void PlayClick(object sender, EventArgs e)
{
VideoControl.Play();
_dispatcherTimer.Start();
}
void dispatcherTimer_Tick(object Sender, EventArgs e)
{
_dispatcherTimer.Stop();
VideoControl.Pause();
}
}
答案 1 :(得分:1)
将定时器的声明输出到私有类变量中,将几行移动到类的构造函数中,并在Tick
处理程序中停止计时器。
您不想继续创建计时器的原因是因为计时器涉及非托管资源,因此您正在关闭该循环。
private dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
ctor
{
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, 10);
}
void PlayClick(object sender, EventArgs e)
{
VideoControl.Play();
dispatcherTimer.Start();
}
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
dispatchTimer.Stop();
VideoControl.Pause();
}
答案 2 :(得分:0)
尝试使用Tick
事件中的以下代码:
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
(sender as DispatcherTimer).Stop();
VideoControl.Pause();
}
您可以在Playclick事件之外设置dispatcherTimer
个对象,并且只能通过以下方式将Start()
方法放入PlayClick
个事件中:
var dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
public Form1() //// form constructor where you are handling these all event....
{
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, 10);
}
void PlayClick(object sender, EventArgs e)
{
VideoControl.Play();
dispatcherTimer .Start();
}