-3

I'm using the Schedule timer www.codeproject.com

But, when working with the listview I received the error below:

Cross-thread operation not valid: Control 'lsViewIm' accessed from a thread other than the thread it was created on.

Here's my code: This is for my button to execute the timer:

delegate void TickHandler(string Profile);
private void btnStart_Click(object sender, EventArgs e)
{
    Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);  

    if(ConfigurationManager.AppSettings.AllKeys.Contains("Stock-Enable"))
    {
        if (config.AppSettings.Settings["Stock-Enable"].Value.ToString() == "Y")
        {
            main.oWriteText(lsViewIm, "Reading... " + DateTime.Now.ToString(), Color.Black, false, "logs"); 

            IScheduledItem Item = GetSchedStock();
            _AlarmTimer.Stop();
            _AlarmTimer.ClearJobs();
            _AlarmTimer.AddJob(Item, new TickHandler(updateStocks), "Woo1");
            _AlarmTimer.Start();
        }
    }
}

private ScheduleTimer _AlarmTimer = new ScheduleTimer();
private IScheduledItem GetSchedStock()
{
    return new ScheduledTime("ByMinute", "1"); 
}

This code will show details to ListView:

public void oWriteText(ListView lsView, string txt, Color? oColor = null, Boolean isStored = false, string oFile = "logs")
{
    ListViewItem addItem = lsView.Items.Add(txt);
    lsView.EnsureVisible(lsView.Items.Count - 1);
    addItem.SubItems[0].ForeColor = oColor ?? Color.Black;
    lsView.Refresh(); 
}

And this is my method, and will put here the rest of the code here.

public void updateStocks(string Profile)
{
    oWriteText(lsViewIm, DateTime.Now.ToString(), Color.Black, false, "logs");
    return;
}
Gimo Gilmore
  • 229
  • 9
  • 23
  • 3
    Look at "Related" on the right. There are about 10,000 "Cross-thread operation not valid" questions already answered. – MrZander May 17 '17 at 16:40
  • @MrZander every single question under related is 'Cross-thread....not valid". literally – TheNoob May 17 '17 at 17:07

1 Answers1

1

Thank you!

From:

    //ListViewItem addItem = lsView.Items.Add(txt);
    //lsView.EnsureVisible(lsView.Items.Count - 1);
    //addItem.SubItems[0].ForeColor = oColor ?? Color.Black;
    //lsView.Refresh(); 

To:

    ListViewItem addItem = null;
    ControlInvoke(lsView, () => addItem = lsView.Items.Add(txt));
    ControlInvoke(lsView, () => addItem.SubItems[0].ForeColor = oColor ?? Color.Black);
    ControlInvoke(lsView, () => lsView.EnsureVisible(lsView.Items.Count - 1));
    ControlInvoke(lsView, () => lsView.Refresh());

delegate void UniversalVoidDelegate(); 
public static void ControlInvoke(Control control, Action function)
{
    if (control.IsDisposed || control.Disposing)
        return;

    if (control.InvokeRequired)
    {
        control.Invoke(new UniversalVoidDelegate(() => ControlInvoke(control, function)));
        return;
    }
    function();
}
Gimo Gilmore
  • 229
  • 9
  • 23