Cross-thread operation not valid - used timer to do someting, but can't hide the form

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • x9990860
    New Member
    • Nov 2009
    • 1

    Cross-thread operation not valid - used timer to do someting, but can't hide the form

    Cross-thread operation not valid: Control 'Form1' accessed from a thread other than the thread it was created on.
    [code=C#]
    using System;
    using System.Collecti ons.Generic;
    using System.Componen tModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows. Forms;
    using System.Timers;

    namespace WindowsFormsApp lication2
    {
    public partial class Form1 : Form
    {
    private static System.Timers.T imer aTimer;

    public Form1()
    {
    InitializeCompo nent();
    aTimer = new System.Timers.T imer();
    aTimer.Elapsed += new ElapsedEventHan dler(found_card );
    // Set the Interval to 2 seconds.
    aTimer.Interval = 1000;
    aTimer.Enabled = true;

    }

    private void found_card(obje ct sender, EventArgs e)
    {
    aTimer.Enabled = false;

    // use smart card system to find the card. if found the card, it will open form2 and close form1

    Form form2 = new Form2();
    this.Hide(); // <--- error, please help me to make a solution
    form2.ShowDialo g();
    this.Close();
    }
    }
    }
    [/code]
    Last edited by Plater; Nov 18 '09, 02:30 PM. Reason: [code] tags
  • Plater
    Recognized Expert Expert
    • Apr 2007
    • 7872

    #2
    That exception only gets thrown in debug mode, to alert you of what you are doing.
    In the exception message should be a link to MSDN about ways to solve that issue.
    My favorite is using a delegate and invoke.

    For instance in my form I have:
    [code=c#]
    private delegate string ReportInfoCallb ack(string msg);

    private string ReportInfo(stri ng msg)
    {
    if (this.InvokeReq uired)
    {
    ReportInfoCallb ack d = new ReportInfoCallb ack(ReportInfo) ;
    this.Invoke(d, msg);
    }
    else
    {
    tbResults.Appen dText(msg);
    }
    return msg;
    }
    [/code]
    Now from another thread (like a timer) I can call the ReportInfo("Som e text"); function and it will handle the cross threading.

    You can change up the function and the delegate to match your needs for hiding.


    I see that you are also calling this.Close(), once that happens your timer dissapears too

    Comment

    Working...