dcsimg
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 9 of 9

Thread: Questions

  1. #1
    Join Date
    Aug 2009
    Posts
    18

    Questions

    Hi, i'm gonna be working on a new miniproject soon but i need some information before starting; since i believe that Programing with everything planned ahead makes for painless coding !

    Question 1
    As much as i know, there is no OnLoaded event for WinForms, that would be handled when ALL Components of a Form are Loaded and displayed.
    There is only an OnShown event but it only concerns the Form.

    How can i make it so that my Code only runs after all components are fully loaded ?
    i thought about setting a 3 Seconds TimeLap using either Thread.Sleep(3000) or maybe Timer
    But where can i even put it, since it will probably be activated BEFORE THE FORM & it's components are displayed, this is a problem i've been looking to resolve but found no way besides implementing a button and using it's click event, which i don't need .

    Question 2.
    As my Download will have to run on a secondary thread in order not to block the app , i will have to update the Status label's text which was created on the MAIN Thread. How does one do Cross thread opérations such as this one?

    I Heard about 2 things :
    Invoke , but i don't know how it works and i couldn't grasp the concept from the info here, if someone could explain.
    or System.Windows.Form.Control.CheckforIllegalCrossThread set to false !
    which is reported as dangerous, and it seems that MSDN Says that it does not work outside of the debuger?

    Question 3
    A Problem with the progress Bar,
    for the Download , i Believe that to use the Progress Bar control the download has to be Async but my download méthod having already started on a second thread, i don't think that i would need it to be async especially considering that the progress bar is on the main thread (am i right?)
    So how can i use it with DownloadFile instead of Async ?

    The reason is that if i use ASYNC, the Code won't stop and i believe that Thread.Suspend or Wait has been removed from Visual Studio for some reason ,
    and if the code following is executed, it will screw the progress Bar as the Download of the next file will also happen simultaneously which the progress bar can't naturally handle.
    So the solutions i can think of here are :
    - Find a way to stop code execution until completition of Download that is on going.
    - Use DownloadFile as it always blocks until file is completely downloaded


    I Realize there are a lot of questions, but don't hesitate to just throw one idea , thanks !
    Last edited by Rehael; August 15th, 2009 at 06:53 AM.

  2. #2
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,227

    Re: Questions

    Q1 Check out the protected OnLoad method in msdn
    Q2 See this post: http://www.codeguru.com/forum/showthread.php?t=482542

  3. #3
    Join Date
    Aug 2009
    Posts
    18

    Re: Questions

    http://msdn.microsoft.com/en-us/libr...rm.onload.aspx
    They don't even say what it does or when it happens, from my understanding.
    OnLoad <=> When Form is Loading just like OnClose and it's far from what i need :l

  4. #4
    Join Date
    Jun 2004
    Location
    Kashmir, India
    Posts
    6,808

    Re: Questions

    For question 2 & 3, wouldn't a backgroundworker component work? It will make your life little easier when it comes to updating controls/etc from another thread. Look at the same ples provided my MSDN.

    For question1, are you talking about normal windows controls or any user controls that you might have added to the form at the design time?

  5. #5
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,227

    Re: Questions

    Quote Originally Posted by Rehael View Post
    http://msdn.microsoft.com/en-us/libr...rm.onload.aspx
    They don't even say what it does or when it happens, from my understanding.
    OnLoad <=> When Form is Loading just like OnClose and it's far from what i need :l
    If you put your code after the call to base.OnLoad(...), it will do what you are describing. Have you tried testing it out?

  6. #6
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,227

    Re: Questions

    For Q3 - attach a small sample project to show what issues you are running into.

  7. #7
    Join Date
    Aug 2009
    Posts
    18

    Re: Questions

    Quote Originally Posted by Arjay View Post
    If you put your code after the call to base.OnLoad(...), it will do what you are describing. Have you tried testing it out?
    Hi, thanks for trying to help and i fixed it using your idea as base, made a new Event and called it OnLoaded xD

    Code:
    protected override void OnLoad(EventArgs args)
    {
        base.OnLoad(args);
    
        Application.Idle += new EventHandler(OnLoaded);
    }
    
    private void OnLoaded(object sender,
                          EventArgs args)
    {
        Application.Idle -= new EventHandler(OnLoaded);
    
        
    }
    Quote Originally Posted by Arjay View Post
    For Q3 - attach a small sample project to show what issues you are running into.
    Alright.

    This is my Downloader
    Code:
        class Utility
        {
    
            public void Download(Uri url, string path, string status)
            {
                Program.myform.statusLabel.Invoke((ThreadStart)delegate()
              {
                  Program.myform.statusLabel.Text = "Status :" + status;
    
              });
                if (!Directory.Exists(Path.GetDirectoryName(path))) Directory.CreateDirectory(Path.GetDirectoryName(path));
                if (File.Exists(path)) File.Delete(path);
                using (WebClient client = new WebClient())
                {
    
                    DataTreatement.wait = true;
                    client.DownloadProgressChanged +=new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
                    client.DownloadFileCompleted +=new System.ComponentModel.AsyncCompletedEventHandler(client_DownloadFileCompleted);
    
                    try
                    {
                        client.DownloadFileAsync(url, path);
                    }
                    catch { System.Windows.Forms.MessageBox.Show("EXCEPTION TEST"); }
                }
    
            }
    
            void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
            {
                if (Program.myform.statusLabel.InvokeRequired)
                {
                    Program.myform.statusLabel.Invoke((ThreadStart)delegate()
                    {
                        if (Program.myform.statusLabel.Text.Equals("Status : Downloading file"))
                            Program.myform.statusLabel.Text = "Status : Downloading file";
                    });}
                    else Program.myform.statusLabel.Text = "Status : Downloading File";
                    if (Program.myform.progressBar1.InvokeRequired)
                    {
                        Program.myform.progressBar1.Invoke((ThreadStart)delegate()
                         {
                             Program.myform.progressBar1.Value = e.ProgressPercentage;
    
                         });
                    }
                    else
                        Program.myform.progressBar1.Value = e.ProgressPercentage;
                    
    
            }
            void client_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
            {
                if (Program.myform.statusLabel.InvokeRequired)
                {
                    Program.myform.statusLabel.Invoke((ThreadStart)delegate()
                    {
                        Program.myform.statusLabel.Text = "Status : File Download Complete";
                        
                    });
                    
    
                }
                
            }
        }
    The problem is, my app might generate up to 3 Patch Instances !
    and since the DownloadAsync method let's the current parent thread CONTINUE His job,
    Comes a point where badam ! The Second PatchDownload is launched. And this is a situation that i don't want to happen.
    Only 1 !!! patch must happen in one time.

    What i need is a sort of Queue system with a logic that i could define as :

    As long as DownloadCompleted Event isn't raised, WAIT !

  8. #8
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,227

    Re: Questions

    Note that the Form already contains a Load event. Open the Form in the editor, open the property window. Click on the little lightning bolt icon in the properties window and you see the list of available events. Add a Load event handler.

    In terms of patch syncronization you can use a few events (started and completed events) and pass the events into your utility class instances. To avoid blocking the Utility class could create a separate thread that starts the real download operation. Within the thread, just wait on the started event before performing the actual download operation. When the download completes, it sets the completed event.

    I'd recommend that you remove any UI progress bar references in the utility class. You want to avoid this sort of tight coupling between the UI and worker classes.

    Since you have several downloads to complete, you'll create three Utility instances. In the first utility instance, you pass in null for the started event, and an event for the completed event

    Code:
    ManualResetEvent pkg1CompletedEvent = new ManualResetEvent( false );
    ManualResetEvent pkg2CompletedEvent = new ManualResetEvent( false );
    ManualResetEvent pkg3CompletedEvent = new ManualResetEvent( false );
     
    Utility utility1 = Utility.Create( "url1", "path1", null, pkg1CompletedEvent );
    utility1.Progress += newProgressEventHandler(OnProgressChanged);
    utlity1.Start( );
     
    Utility utility2 = Utility.Create( "url2", "path2", pkg1CompletedEvent, pkg2CompletedEvent );
    utility2.Progress += newProgressEventHandler(OnProgressChanged);
    utlity2.Start( );
     
    Utility utility3 = Utility.Create( "url3", "path3", pkg2CompletedEvent, pkg3CompletedEvent );
    utility3.Progress += newProgressEventHandler(OnProgressChanged);
    utility3.Completed += new CompletedEventHandler(OnCompleted);
    utlity3.Start( );

  9. #9
    Join Date
    Aug 2009
    Posts
    18

    Re: Questions

    thanks looks like a plan, events ftw !

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width




On-Demand Webinars (sponsored)