使用Thread刷新Progressbar UI

时间:2013-02-22 15:28:49

标签: c#

我有一个没有UI运行的FTP进程。并有一个使用此ftp控件的winform。在那个窗口中,我有一个显示ftp上传进度的进度条。进度通过在底层演示者上更新的interfase到达窗口(我正在使用MVP模式)。

我的问题是当尝试更新进度时,总是把这个异常抛给我。

通过线程非法操作:从你创建它的线程以外的线程访问控制'prgProgresoSubido'。

即使我在表单中使用BackGroundWorker,问题仍然存在。

    // This is  a delegated on presenter when a File finish to upload
    void client_FileUploadCompletedHandler(object sender, FileUploadCompletedEventArgs e)
    {
        string log = string.Format("{0} Upload from {1} to {2} is completed. Length: {3}. ",
            DateTime.Now, e.LocalFile.FullName, e.ServerPath, e.LocalFile.Length);

        archivosSubidos += 1;
        _Publicacion.ProgresoSubida = (int)((archivosSubidos / archivosXSubir) * 100);
        //this.lstLog.Items.Add(log);
        //this.lstLog.SelectedIndex = this.lstLog.Items.Count - 1;
    }


    // This is My interfase 

public interface IPublicacion
{
    ...
    int ProgresoSubida { set; } 
}

/// And Here is the implementartion of the interfase on the form

public partial class PublicarForm : Form ,IPublicacion 
{
    //Credenciales para conectarse al servicio FTP 
    public FTPClientManager client = null;
    public XmlDocument conf = new XmlDocument();
    public string workingDir = null;
    public webTalk wt = new webTalk();
    private readonly PublicacionesWebBL _Publicador;

    public PublicarForm()
    {
        InitializeComponent();

        String[] laPath = { System.AppDomain.CurrentDomain.BaseDirectory};
        String lcPath = System.IO.Path.Combine(laPath);

        _Publicador = new PublicacionesWebBL(this, lcPath);
    }

    public int ProgresoSubida
    {
        set
        {
            //  This is my prograss bar, here it throw the exception.
            prgProgresoSubido.Value = value;
        }
    }
}

如何避免此问题?

2 个答案:

答案 0 :(得分:2)

通常,用户界面和控件的所有更新都必须从主线程(事件调度程序)完成。如果您尝试从其他线程修改控件的属性,则会出现异常。

您必须调用Control.Invoke以在事件调度程序上调用更新UI的方法

Control.Invoke

在这里,在表单上放置一个按钮和一个标签,然后尝试这个

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Thread t = new Thread(new ThreadStart(TestThread));
        t.Start();
    }

    private void TestThread()
    {
        for (int i = 0; i < 10; i++)
        {
            UpdateCounter(i);
            Thread.Sleep(1000);
        }
    }

    private void UpdateCounter(int i)
    {


        if (label1.InvokeRequired)
        {
            label1.Invoke(new ThreadStart(delegate { UpdateCounter(i); }));
        }
        else
        {
            label1.Text = i.ToString();
        }
    }
}

意识到,如果从一个线程触发事件,该事件将在同一个线程上。因此,如果该线程不是事件调度程序,则需要调用。

此外,BackgroundWorker可能会为您提供一些机制(正如评论员所说)为您简化此操作,但我之前从未使用过这些机制,因此我会将此留给您进行调查。

答案 1 :(得分:1)

正如Alan刚刚指出的那样,你必须在UI线程中使用UI控件进行所有操作。

只需修改您的属性:

public int ProgresoSubida
{
    set
    {
        MethodInvoker invoker = delegate
                                {
                                    prgProgresoSubido.Value = value;
                                }
        if (this.InvokeRequired)
        {
            Invoke(invoker);
        }
        else
        {
            invoker();
        }

    }
}
相关问题