简体   繁体   English

标签控件未显示在for循环C#中

[英]Label control does not display in for loop c#

I am new to programming world, kindly be gentle and my question is why the label control does not displaying file name one by one when it is called in for each loop. 我是编程界的新手,请保持柔和,我的问题是,为什么在每个循环中调用标签控件时,标签控件都不一一显示文件名。 My task is to read the folder which contains more files I need to read the file name and display in the label control but it is not working well for me, it is simple for all but I am a beginner Why I don't know find how to find out the mistake? 我的任务是读取包含更多文件的文件夹,我需要阅读该文件名并显示在标签控件中,但对我而言效果不佳,对所有人来说都很简单,但我是初学者为什么不知道查找如何找出错误?

Please find the code. 请找到代码。

namespace ImageScanning
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #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 InitializeComponent()
        {
            this.label1 = new System.Windows.Forms.Label();
            this.button1 = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(21, 79);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(81, 13);
            this.label1.TabIndex = 0;
            this.label1.Text = "File scanning-->";
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(27, 144);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 1;
            this.button1.Text = "button1";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(284, 262);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.label1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.Load += new System.EventHandler(this.Form1_Load);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Button button1;
    }
}

Button Click Event is: 按钮单击事件为:

private void button1_Click(object sender, EventArgs e)
{
     string imageloc = @"D:\Image";
     string[] files = Directory.GetFiles(imageloc);
     foreach (string file in files)
     {
          System.Threading.Thread.Sleep(1000);
          label1.Text = "File Scanning--> " + file;
          System.Threading.Thread.Sleep(3000);
          label1.Text = "";
     } 
}

You need to use threading, while running loop iterations, UI thread was busy and UI part is waiting for the event to complete before reflecting the change labels and other UI controls, so you need to start another thread for loop iterations then UI thread will be free to update UI. 您需要使用线程,在运行循环迭代时,UI线程忙,并且UI部件在反映更改标签和其他UI控件之前正在等待事件完成,因此您需要启动另一个线程进行循环迭代,然后UI线程将成为免费更新用户界面。

Try this 尝试这个

private void button1_Click(object sender, EventArgs e)
{
    Task.Factory.StartNew(() =>
    {
         string imageloc = @"D:\Image";
         string[] files = Directory.GetFiles(imageloc);
         foreach (string file in files)
         {
             System.Threading.Thread.Sleep(1000);
             // Any UI control which you want to use within thread,
             // you need Invoke using UI thread. I have declare a method below

             ExecuteSecure(() => label1.Text = "File Scanning--> " + file);
             System.Threading.Thread.Sleep(3000);
             ExecuteSecure(() => label1.Text = "");    
         }          
    });        
}    

//---
private void ExecuteSecure(Action action)
{
    if (InvokeRequired)
    {
        Invoke(new MethodInvoker(() => action()));
    }
    else
    {
        action();
    }
}

Here is a sample code using the background worker process 这是使用后台工作进程的示例代码

BackgroundWorker bw = new BackgroundWorker();
public Form1()
{
    InitializeComponent();

    bw.WorkerReportsProgress = true;
    bw.DoWork += bw_DoWork;
    bw.ProgressChanged += bw_ProgressChanged;
}

void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
   label1.Text = "File Scanning --> " + e.UserState as string;     
}

void bw_DoWork(object sender, DoWorkEventArgs e)
{
    string imageloc = @"D:\Image";
    string[] files = Directory.GetFiles(imageloc);
    foreach (var item in files)
    {
       bw.ReportProgress(0, item);
       Thread.Sleep(1000);
    }
 }

protected void button1_Click(object sender, EventArgs e)
{
   if (!bw.IsBusy)
   {
       bw.RunWorkerAsync();
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM