locked
Visible Property RRS feed

  • Question

  • Hi,

    I want to run a sql query in my app when a button is clicked on, before running the query I want a gif picture to become visible, it's like a clock I want to use it instead of progress bar. what I need to just to change its visibility property to true and then when the query is over, again change it back to false.

    but when I do that, I can't see it. the query will run without the icon become visible at first.

    If i don't change it back to false, I can see it after the query is over, which is when I don't want it anymore.

    I don't know what I am missing here, when I make something visible, isn't that supposed to be instant?

    I appreciate your help. I know it's probably simple, but I can't get it to work!

    Regards,

     

    Friday, July 22, 2011 10:19 PM

Answers

  • Try this men:
     
    BackgroundWorker worker = new BackgroundWorker();
    worker.DoWork += new DoWorkEventHandler(worker_DoWork);
    worker.RunWorkerCompleted += new workerCompletedEventHandler(worker_RunWorkerCompleted);
    worker.RunWorkerAsync();
    
    void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
       MessageBox.Show(e.Result.ToString());
    }
    
    void worker_DoWork(object sender, DoWorkEventArgs e)
    {
       e.Result = "Hello world!";
    }
    

    Profesional Microsoft VIP | México
    • Marked as answer by Cookie Luo Wednesday, August 3, 2011 5:56 AM
    Tuesday, July 26, 2011 11:00 PM

All replies

  • The CPU may be busy running your query instead of displaying your 'clock'.  Timing and the order in which things occur is everything.  You posted no code.

    I don't know how you display your image, I assume that you are using a PictureBox control.  If you are using a PictureBox, then you may try to set the Image property of the control, set the Visible property of the control, and finally call Invalidate on the control to update it.  Now, run your query.

    Rudy   =8^D


    Mark the best replies as answers. "Fooling computers since 1971."

    http://thesharpercoder.blogspot.com/

    Friday, July 22, 2011 10:24 PM
  • Saturday, July 23, 2011 4:09 AM
  • 2 more options.

    1. Use backgroundworker for the sqlquery. That way,

    the query will be hadled on a different thread. Thus, your main thread would be free to show the image.

    2. Use Application.DoEvents() in order to do all the actions that are waiting.

    Method 1 is the best method.

     

    Noam B.



    Do not Forget to Vote as Answer/Helpful, please. It encourages us to help you...
    • Proposed as answer by Noam B Wednesday, July 27, 2011 6:01 AM
    Sunday, July 24, 2011 11:44 AM
  • I would not recommending using DoEvents at all.  It can cause unexpected results because you cannot predict every action that may have taken when it is called by your code.  DoEvents will cause any and all pending event messages to be processed with a priority that supersedes your code. 

    A more reliable solution would be to use a BGW as you suggested, which has a ReportProgress method that invokes the main thread for you and returns execution to your worker thread.  Another mechanism built into the .NET Framework is the APM, Asynchronous Programming Model.  See this thread, and the links on it.

    http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/6923b518-8c87-4136-b387-6d198a756155

    The following thread can be found in a link that I posted in the above thread.

    http://social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/faa5da25-f50c-4a87-b1e8-ed7a6ec8cd71

    That thread contains a layman's explanation that I posted of the APM and the Control.InvokeRequired property.

    Rudy   =8^D


    Mark the best replies as answers. "Fooling computers since 1971."

    http://thesharpercoder.blogspot.com/

    Sunday, July 24, 2011 12:36 PM
  • Welcome to MSDN Forums.

    You reached an issue that I reached too when I started C# coding for business :)

    Let's discuss the concept behind: "CPU cannot do two pieces of code in same time except running them in different threads!". when you write code, they will be executed in main thread by default except when you create a thread and run a piece of code in it. In your case, the query should run in seperate thread and the main thread should process that image and wait for end of the another thread. please see more at http://msdn.microsoft.com/en-us/library/ms173178(v=vs.80).aspx (Threading (C# Programming Guide)). BackgroundWorker component is a wrapper of this concept which is more easier to use than directly with threads.

    But more nice solution can be using:

    • SqlCommand.BeginExecuteNonQuery
      using System.Data.SqlClient;
      
      class Class1
      {
        static void Main()
        {
          // This is a simple example that demonstrates the usage of the 
          // BeginExecuteNonQuery functionality.
          // The WAITFOR statement simply adds enough time to prove the 
          // asynchronous nature of the command.
      
          string commandText = 
            "UPDATE Production.Product SET ReorderPoint = ReorderPoint + 1 " + 
            "WHERE ReorderPoint Is Not Null;" + 
            "WAITFOR DELAY '0:0:3';" + 
            "UPDATE Production.Product SET ReorderPoint = ReorderPoint - 1 " + 
            "WHERE ReorderPoint Is Not Null";
      
          RunCommandAsynchronously(commandText, GetConnectionString());
      
          Console.WriteLine("Press ENTER to continue.");
          Console.ReadLine();
        }
      
        private static void RunCommandAsynchronously(
          string commandText, string connectionString)
        {
          // Given command text and connection string, asynchronously execute
          // the specified command against the connection. For this example,
          // the code displays an indicator as it is working, verifying the 
          // asynchronous behavior. 
          using (SqlConnection connection = 
                new SqlConnection(connectionString))
          {
            try
            {
              int count = 0;
              SqlCommand command = new SqlCommand(commandText, connection);
              connection.Open();
      
              IAsyncResult result = command.BeginExecuteNonQuery();
              while (!result.IsCompleted)
              {
                Console.WriteLine("Waiting ({0})", count++);
                // Wait for 1/10 second, so the counter
                // does not consume all available resources 
                // on the main thread.
                System.Threading.Thread.Sleep(100);
              }
              Console.WriteLine("Command complete. Affected {0} rows.", 
                command.EndExecuteNonQuery(result));
            }
            catch (SqlException ex)
            {
              Console.WriteLine("Error ({0}): {1}", ex.Number, ex.Message);
            }
            catch (InvalidOperationException ex)
            {
              Console.WriteLine("Error: {0}", ex.Message);
            }
            catch (Exception ex)
            {
              // You might want to pass these errors
              // back out to the caller.
              Console.WriteLine("Error: {0}", ex.Message);
            }
          }
        }
      
        private static string GetConnectionString()
        {
          // To avoid storing the connection string in your code,      
          // you can retrieve it from a configuration file. 
      
          // If you have not included "Asynchronous Processing=true" in the
          // connection string, the command is not able
          // to execute asynchronously.
          return "Data Source=(local);Integrated Security=SSPI;" +
            "Initial Catalog=AdventureWorks; Asynchronous Processing=true";
        } 
      }
      
    • SqlCommand.BeginExecuteReader
      using System.Data.SqlClient;
      
      class Class1
      {
        static void Main()
        {
          // This is a simple example that demonstrates the usage of the 
          // BeginExecuteReader functionality
          // The WAITFOR statement simply adds enough time to prove the 
          // asynchronous nature of the command.
          string commandText =
            "WAITFOR DELAY '00:00:03';" +
            "SELECT LastName, FirstName FROM Person.Contact " +
            "WHERE LastName LIKE 'M%'";
      
          RunCommandAsynchronously(commandText, GetConnectionString());
      
          Console.WriteLine("Press ENTER to continue.");
          Console.ReadLine();
        }
      
        private static void RunCommandAsynchronously(
          string commandText, string connectionString)
        {
          // Given command text and connection string, asynchronously execute
          // the specified command against the connection. For this example,
          // the code displays an indicator as it is working, verifying the 
          // asynchronous behavior. 
          using (SqlConnection connection = new SqlConnection(connectionString))
          {
            try
            {
              SqlCommand command = new SqlCommand(commandText, connection);
      
              connection.Open();
              IAsyncResult result = command.BeginExecuteReader();
      
              // Although it is not necessary, the following code
              // displays a counter in the console window, indicating that 
              // the main thread is not blocked while awaiting the command 
              // results.
              int count = 0;
              while (!result.IsCompleted)
              {
                count += 1;
                Console.WriteLine("Waiting ({0})", count);
                // Wait for 1/10 second, so the counter
                // does not consume all available resources 
                // on the main thread.
                System.Threading.Thread.Sleep(100);
              }
      
              using (SqlDataReader reader = command.EndExecuteReader(result))
              {
                DisplayResults(reader);
              }
            }
            catch (SqlException ex)
            {
              Console.WriteLine("Error ({0}): {1}", ex.Number, ex.Message);
            }
            catch (InvalidOperationException ex)
            {
              Console.WriteLine("Error: {0}", ex.Message);
            }
            catch (Exception ex)
            {
              // You might want to pass these errors
              // back out to the caller.
              Console.WriteLine("Error: {0}", ex.Message);
            }
          }
        }
      
        private static void DisplayResults(SqlDataReader reader)
        {
          // Display the data within the reader.
          while (reader.Read())
          {
            // Display all the columns. 
            for (int i = 0; i < reader.FieldCount; i++)
              Console.Write("{0} ", reader.GetValue(i));
            Console.WriteLine();
          }
        }
      
        private static string GetConnectionString()
        {
          // To avoid storing the connection string in your code,      
          // you can retrieve it from a configuration file. 
      
          // If you have not included "Asynchronous Processing=true" in the
          // connection string, the command is not able
          // to execute asynchronously.
          return "Data Source=(local);Integrated Security=true;" +
            "Initial Catalog=AdventureWorks; Asynchronous Processing=true";
        }
      }
      

    Sincerely,

    Yasser

    Sunday, July 24, 2011 1:34 PM
  • This didn't work Rudedog2

    I tried it but I still don't see it.

    Thanks anyway


    Amir
    Tuesday, July 26, 2011 10:20 PM
  • I want to go with the background worker, what I did is this, is this wrong:

    when I run the program nothing happens, it skips going into back ground worker block:

    private void btnRun_Click(object sender, EventArgs

    e)

    {

     this.picTimer.Visible = true;

    picTimer.Invalidate();

    this.Cursor = Cursors.WaitCursor;

    tabReportDetails.Enabled= true

    ;

    dgrdReceiving.Rows.Clear();

    backgroundWorker1.RunWorkerAsync();

     picTimer.Visible = false;

     this.Cursor = Cursors

    .Default;

     }

     

    .

    .

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)

    {

    showReceivingResults();

    return;

     }


    Amir
    Tuesday, July 26, 2011 10:24 PM
  • Try this men:
     
    BackgroundWorker worker = new BackgroundWorker();
    worker.DoWork += new DoWorkEventHandler(worker_DoWork);
    worker.RunWorkerCompleted += new workerCompletedEventHandler(worker_RunWorkerCompleted);
    worker.RunWorkerAsync();
    
    void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
       MessageBox.Show(e.Result.ToString());
    }
    
    void worker_DoWork(object sender, DoWorkEventArgs e)
    {
       e.Result = "Hello world!";
    }
    

    Profesional Microsoft VIP | México
    • Marked as answer by Cookie Luo Wednesday, August 3, 2011 5:56 AM
    Tuesday, July 26, 2011 11:00 PM
  • Please take a look at the this thread for a demonstration of how to use a BackgroundWorker to update a form.

    http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/52dcb460-90a3-45f2-ae23-bcb60514c542/

    The demo updates a ProgressBar using simple loop.  Copy the sample code into a *CLASS* file, not a new form file. 

    Rudy   =8^D


    Mark the best replies as answers. "Fooling computers since 1971."

    http://thesharpercoder.blogspot.com/


    Wednesday, July 27, 2011 10:16 PM