How to do when clicking the execute action button every 1 second

0

I'm using CefSharp and wanted it when I clicked the button to run the javascript every 1 second and in the background too, and only stop if I click the shutdown button. I tried the backgroundworker but I could not, I'm kind of lazy in that part:

When you click the button the background worker executes:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    bool rodando = true;

    chromeBrowser.ExecuteScriptAsync("$(document).ready(function(){if($('#signup_button').is(':visible')){alert('Você precisa estar logado para utilizar o script')}})");

    try
    {
        Thread t = new Thread(() => 
        {
            while (rodando)
            {
                Thread.Sleep(1000);
                Script();
            }
        });

        t.Start();
    }
    catch
    {

    }
}

Shutdown button:

private void btnscriptshutdown_Click(object sender, EventArgs e)
{
    if (worker.WorkerSupportsCancellation)
        worker.CancelAsync();
}

Just do not do the loop, just run once, how can I do to always execute?

    
asked by anonymous 27.05.2018 / 22:13

1 answer

0

Instead of using BackgroundWorker , you can use Timer , of the System.Timers.Timer library.

Your code can be done as follows:

System.Timers.Timer _timer;

public Form1()
{
    InitializeComponent();

    // Botão para iniciar a thread
    btnStart.Click += Start_Click;

    // Botão para encerrar a thread
    btnStop.Click += Stop_Click;
}

private void Start_Click(object sender, EventArgs e)
{
    // Cria e inicia o timer para ser disparado a cada 1 segundo = (1000 ms)
    if (_timer == null)
    {
        chromeBrowser.ExecuteScriptAsync("$(document).ready(function(){if($('#signup_button').is(':visible')){alert('Você precisa estar logado para utilizar o script')}})");

        _timer = new System.Timers.Timer();
        _timer.Interval = 1000;
        _timer.Elapsed += Timer_Elapsed;
        _timer.Start();
    }
    else
    {
        MessageBox.Show("Já existe uma tarefa em andamento!");
    }
}

private void Stop_Click(object sender, EventArgs e)
{
    // Encerra o timer, se estiver ativo
    if (_timer != null && _timer.Enabled)
    {
        _timer.Stop();
        _timer.Enabled = false;
        _timer = null;
    }
}

// Código executado a cada 1 segundo
private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    Script();
}

In this example, Form has two buttons: btnStart that starts thread and btnStop , which stops thread .

The Timer_Elapsed method is responsible for running your code every 1 second.

Important

Since your code is now running on a thread separate from the main thread, if you need to update any information on the screen, such as Label text, you should run its code on thread master using Invoke .

Example

lblSeconds.Invoke(new Action(() =>
{
    lblSeconds.Text = "Label atualizado a partir de outra thread.";
}));
    
28.05.2018 / 19:41