Threads, textboxes and scrolling

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Wesman

    #1

    Threads, textboxes and scrolling

    Threads, textboxes and scrolling

    Thanks in advance for any information on this matter. I have run into
    a small richtextbox, scrolling and tread issue. Which has me totally
    confused. Instead of trying to explain it I wrote some small C# code
    to demonstrate the fact that in the threaded version the textbox
    simple doesn't scroll like it should… please look to the
    startButton_Cli ck method for the distinction between the two
    programs..

    Thanks

    Wesley

    why does this work ?????????????


    using System;
    using System.Drawing;
    using System.Collecti ons;
    using System.Componen tModel;
    using System.Windows. Forms;
    using System.IO;
    using System.Data;

    namespace Test
    {
    /// <summary>
    /// Summary description for Form1.
    /// </summary>
    public class Test : System.Windows. Forms.Form
    {
    const string newline = "\r\n";

    /// <summary>
    /// Required designer variable.
    /// </summary>

    private System.Windows. Forms.Button startButton;
    private System.Windows. Forms.RichTextB ox output;
    private System.Componen tModel.Containe r components = null;

    public Test()
    {
    InitializeCompo nent();
    }

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    protected override void Dispose( bool disposing )
    {
    if( disposing )
    {
    if (components != null)
    {
    components.Disp ose();
    }
    }
    base.Dispose( disposing );
    }

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
    Application.Run (new Test());
    }

    #region Windows Form Designer generated code
    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeCompo nent()
    {
    this.startButto n = new System.Windows. Forms.Button();
    this.output = new System.Windows. Forms.RichTextB ox();
    this.SuspendLay out();
    //
    // startButton
    //
    this.startButto n.Anchor = (System.Windows .Forms.AnchorSt yles.Top |
    System.Windows. Forms.AnchorSty les.Right);
    this.startButto n.Location = new System.Drawing. Point(424, 8);
    this.startButto n.Name = "startButto n";
    this.startButto n.TabIndex = 0;
    this.startButto n.Text = "Start";
    this.startButto n.Click += new
    System.EventHan dler(this.start Button_Click);
    //
    // output
    //
    this.output.Anc hor = (((System.Windo ws.Forms.Anchor Styles.Top |
    System.Windows. Forms.AnchorSty les.Bottom)
    | System.Windows. Forms.AnchorSty les.Left)
    | System.Windows. Forms.AnchorSty les.Right);
    this.output.Loc ation = new System.Drawing. Point(0, 40);
    this.output.Nam e = "output";
    this.output.Siz e = new System.Drawing. Size(512, 296);
    this.output.Tab Index = 1;
    this.output.Tex t = "";
    //
    // Form1
    //
    this.AutoScaleB aseSize = new System.Drawing. Size(5, 13);
    this.ClientSize = new System.Drawing. Size(512, 334);
    this.Controls.A ddRange(new System.Windows. Forms.Control[] {
    this.output,
    this.startButto n});
    this.Name = "Form1";
    this.Text = "Backup Utility";
    this.ResumeLayo ut(false);

    }
    #endregion



    /// <summary>
    /// this method takes the giving string and writes it to the
    richtextbox.
    /// this method appends a new line at the end of the input string to
    facilite
    /// returns and scrolling to the botton.. callers need not add a
    newline.
    /// </summary>
    /// <param name="msg">stri ng</param>
    private void DisplayNewEvent (string msg)
    {
    output.AppendTe xt(msg + newline);
    output.Focus();
    output.Selectio nStart = output.Text.Len gth + 1;
    output.Selectio nLength = 0;
    output.ScrollTo Caret();
    }

    private void startButton_Cli ck(object sender, System.EventArg s e)
    {
    GoThroughMyDocu ments();
    }

    /// <summary>
    /// this functions goes through all the folders and files and places
    the
    /// filename in the richtext box...
    /// </summary>
    private void GoThroughMyDocu ments()
    {
    DirectoryInfo info = new DirectoryInfo(
    @"C:\Documen ts and Settings\" +
    SystemInformati on.UserName +
    @"\My Documents");

    RecursivelyTran sverseFilesAndF olders(info.Get Directories());
    GetFileName(inf o.GetFiles());
    }

    //recursively find all the files in all directories in "My
    Documents"
    private void RecursivelyTran sverseFilesAndF olders(Director yInfo[]
    directories)
    {
    if(directories! =null)
    foreach(Directo ryInfo dir in directories)
    {
    RecursivelyTran sverseFilesAndF olders(dir.GetD irectories());
    GetFileName(dir .GetFiles());
    }
    }

    // get each file name and print its full path to the text box
    private void GetFileName(Fil eInfo[] info)
    {
    if(info!=null)
    foreach(FileInf o file in info)
    DisplayNewEvent (file.FullName) ;
    }
    }
    }


    and this not work??????????

    using System;
    using System.Drawing;
    using System.Collecti ons;
    using System.Componen tModel;
    using System.Windows. Forms;
    using System.IO;
    using System.Data;
    using System.Threadin g;

    namespace ThreadTest
    {
    /// <summary>
    /// Summary description for Form1.
    /// </summary>
    public class ThreadTest : System.Windows. Forms.Form
    {
    const string newline = "\r\n";

    Thread worker1;


    /// <summary>
    /// Required designer variable.
    /// </summary>

    private System.Windows. Forms.Button startButton;
    private System.Windows. Forms.RichTextB ox output;
    private System.Componen tModel.Containe r components = null;

    public ThreadTest()
    {
    InitializeCompo nent();
    }

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    protected override void Dispose( bool disposing )
    {
    if( disposing )
    {
    if (components != null)
    {
    components.Disp ose();
    }
    }
    base.Dispose( disposing );
    }

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
    Application.Run (new ThreadTest());
    }

    #region Windows Form Designer generated code
    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeCompo nent()
    {
    this.startButto n = new System.Windows. Forms.Button();
    this.output = new System.Windows. Forms.RichTextB ox();
    this.SuspendLay out();
    //
    // startButton
    //
    this.startButto n.Anchor = (System.Windows .Forms.AnchorSt yles.Top |
    System.Windows. Forms.AnchorSty les.Right);
    this.startButto n.Location = new System.Drawing. Point(424, 8);
    this.startButto n.Name = "startButto n";
    this.startButto n.TabIndex = 0;
    this.startButto n.Text = "Start";
    this.startButto n.Click += new
    System.EventHan dler(this.start Button_Click);
    //
    // output
    //
    this.output.Anc hor = (((System.Windo ws.Forms.Anchor Styles.Top |
    System.Windows. Forms.AnchorSty les.Bottom)
    | System.Windows. Forms.AnchorSty les.Left)
    | System.Windows. Forms.AnchorSty les.Right);
    this.output.Loc ation = new System.Drawing. Point(0, 40);
    this.output.Nam e = "output";
    this.output.Siz e = new System.Drawing. Size(512, 296);
    this.output.Tab Index = 1;
    this.output.Tex t = "";
    //
    // Form1
    //
    this.AutoScaleB aseSize = new System.Drawing. Size(5, 13);
    this.ClientSize = new System.Drawing. Size(512, 334);
    this.Controls.A ddRange(new System.Windows. Forms.Control[] {
    this.output,
    this.startButto n});
    this.Name = "Form1";
    this.Text = "Backup Utility";
    this.ResumeLayo ut(false);

    }
    #endregion



    /// <summary>
    /// this method takes the giving string and writes it to the
    richtextbox.
    /// this method appends a new line at the end of the input string to
    facilite
    /// returns and scrolling to the botton.. callers need not add a
    newline.
    /// </summary>
    /// <param name="msg">stri ng</param>
    private void DisplayNewEvent (string msg)
    {
    output.AppendTe xt(msg + newline);
    output.Focus();
    output.Selectio nStart = output.Text.Len gth + 1;
    output.Selectio nLength = 0;
    output.ScrollTo Caret();
    }

    private void startButton_Cli ck(object sender, System.EventArg s e)
    {
    worker1 = new Thread(new ThreadStart(GoT hroughMyDocumen ts));
    worker1.Start() ;

    // primary thread continues its execution while the worker goes
    // throught its laborous task.
    }

    /// <summary>
    /// this functions goes through all the folders and files and places
    the
    /// filename in the richtext box...
    /// </summary>
    private void GoThroughMyDocu ments()
    {
    DirectoryInfo info = new DirectoryInfo(
    @"C:\Documen ts and Settings\" +
    SystemInformati on.UserName +
    @"\My Documents");

    RecursivelyTran sverseFilesAndF olders(info.Get Directories());
    GetFileName(inf o.GetFiles());
    worker1.Abort() ;
    }

    //recursively find all the files in all directories in "My
    Documents"
    private void RecursivelyTran sverseFilesAndF olders(Director yInfo[]
    directories)
    {
    if(directories! =null)
    foreach(Directo ryInfo dir in directories)
    {
    RecursivelyTran sverseFilesAndF olders(dir.GetD irectories());
    GetFileName(dir .GetFiles());
    }
    }

    // get each file name and print its full path to the text box
    private void GetFileName(Fil eInfo[] info)
    {
    if(info!=null)
    foreach(FileInf o file in info)
    DisplayNewEvent (file.FullName) ;
    }
    }
    }
  • Michael Mayer

    #2
    Re: Threads, textboxes and scrolling

    I hit the wrong "reply" button again. maybe it's time to change
    newsreaders...

    ----- Original Message -----
    From: "Wesman" <wesmanjunk@hot mail.com>[color=blue]
    > Thanks in advance for any information on this matter. I have run into
    > a small richtextbox, scrolling and tread issue. Which has me totally
    > confused. Instead of trying to explain it I wrote some small C# code
    > to demonstrate the fact that in the threaded version the textbox
    > simple doesn't scroll like it should. please look to the
    > startButton_Cli ck method for the distinction between the two
    > programs..[/color]


    Well, the first thing I noticed in Form2 is that it appears you are trying
    to update a UI from another thread. That is, you start a new thread with
    the method:
    GoThroughMyDocu ments
    that calls
    GetFileName
    which finally calls
    DisplayNewEvent
    This method works with the UI. However, it is not running on the same
    thread as the UI (sometimes called the UI thread). Big no-no.

    See this article for info:
    http://msdn.microsoft.com/msdnmag/is...g/default.aspx

    Replace your GetFileName() with something like the following, and it seems
    to work a lot better...

    delegate void DisplayFilename Handler (string text);

    // get each file name and print its full path to the text box
    private void GetFileName(Fil eInfo[] info)
    {
    DisplayFilename Handler show = new DisplayFilename Handler
    (DisplayNewEven t);
    if(info!=null)
    foreach(FileInf o file in info)
    {
    output.Invoke (show, new object[] {file.FullName} );
    //DisplayNewEvent (file.FullName) ;
    }
    }

    Additionally, i'd be tempted to add a cancel button. The above article
    should give you some tips on doing that. I'd suggest inheriting from the
    authors AsyncOperation class to create your "worker" class. Put all your
    code in "DoWork" with checks for the canceled flag, and using his event
    firing methods to assist with updating the UI.


    Mike Mayer

    mmayer1@mag37.c om


    Comment

    Working...