使用c#(包括代码)删除延迟时间:System.Threading.Thread.Sleep

本文关键字:System Threading Thread Sleep 延迟时间 删除 包括 代码 使用 | 更新日期: 2023-09-27 18:15:31

我有一个winform应用程序,它及时显示一些信息,每次加载数据时,我设置7秒的延迟时间,如下所示:System.Threading.Thread.Sleep(7000),以便可以查看信息。我想有一个按钮,可以让我直接跳到下一个信息

我使用的逻辑如下:获取信息,如果有,等待7秒,下一个数据,等等。因此,如果我按下按钮,我想将时间设置为0。

有办法取消等待期吗?

下面是代码:
ManualResetEvent wait_handle = new ManualResetEvent(true);

{…}

private void TheLoop(object stateinfo)
    {
        bool hasInfo = true;            
        bool hasLines = GetLinesOnProduction();
        while (doLoop)
        {
            wait_handle.WaitOne();
            if (hasLines)
            {
                param1 = Lines[CurrentLine].line;
                param2 = Lines[CurrentLine].WO;
                //Here I query the DB for the CurrentLine Data                    
                ShowLineInformation(CurrentLine);
                ShowChartByHour(param1, param2, out hasInfo);
                if (hasInfo)
                    System.Threading.Thread.Sleep(7000);                                        
                //Here I move to the next line
                if (CurrentLine < Lines.Count - 1)
                    CurrentLine++;
                else
                {
                    CurrentLine = 0;  //Start all over again
                    hasLines = GetLinesOnProduction();
                }
            }
            else
            {
                System.Threading.Thread.Sleep(40000);  //(No Lines)Wait to query for lines again
                hasLines = GetLinesOnProduction();
            }
        }
    }
private void btnPauseResume_Click(object sender, EventArgs e)
    {
        if (btnPauseResume.Text == "Pause")
        {
            btnPauseResume.Text = "Resume";
            wait_handle.Reset();
        }
        else
        {
            btnPauseResume.Text = "Pause";
            wait_handle.Set();
        }
    }

使用c#(包括代码)删除延迟时间:System.Threading.Thread.Sleep

不做线程。睡眠时,您可以使用等待事件,并简单地设置它来取消等待。像这样:

var waiter = new AutoResetEvent(false);
bool wasCanceled = waiter.WaitOne(7000);
if(wasCanceled)
    // Jump to next...

// Cancel the wait from another thread
waiter.Set()

而不是使用Thread.Sleep,它将挂起UI中的所有活动,而是使用计时器。使用计时器,当计时器回调挂起时,UI仍然可以响应事件,当您单击该按钮时,您可以取消计时器。

我将通过lockobject设置延迟,然后执行监视器。等待7秒的延迟。然后,从表单中,当按钮被按下时,lock object并执行Monitor.PulseAll.

你可以使用ManualResetHandle:

// Declare it as class member
ManualResetHandle _manualResetHandle = new ManualResetHandle();
// Wait in your process for seven seconds, or until it is Set()
_manualResetHandle.WaitOne(7000);
// Set() it in your click event handler:
_manualResetHandle.Set();