Visualizzazione dei risultati da 1 a 3 su 3
  1. #1

    [C#] Accesso a Strumenti fuori dal Thread

    Salve,
    devo creare un nuovo Thread da "Form1" e gestire l'avanzamento della ProgressBar che si trova in "Form1" dal nuovo Thread, come posso fare ???

    codice:
    namespace Test_Thread
    {
        public partial class Form1 : Form
        {
            Thread t;
    
    
            public Form1()
            {
                InitializeComponent();
            }
    
            private void btnStart_Click(object sender, EventArgs e)
            {
                DataThread data = new DataThread(progressBar1);
    
                t = new Thread(new ParameterizedThreadStart(TestThread));
                t.Start(data);
            }
    
            public void TestThread(object data)
            {
                if (data != null)
                {
                    ((DataThread)data).PBar.Maximum = 100;
    
                    int n = 1000;
    
                    for (int i = 0; i <= n; i++)
                    {
                        ((DataThread)data).PBar.PerformStep();
                    }
                }
            }
        }
    
    
    
        class DataThread
        {
            private ProgressBar m_oPb;
    
            public DataThread(ProgressBar _oPb)
            {
                m_oPb = _oPb;
            }
    
            public ProgressBar PBar
            {
                get { return m_oPb; }
            }
        }
    }
    mi restituisce questo errore:

    Cross-thread operation not valid: Control 'progressBar1' accessed from a thread other than the thread it was created on.

  2. #2
    Moderatore di Programmazione L'avatar di alka
    Registrato dal
    Oct 2001
    residenza
    Reggio Emilia
    Messaggi
    24,472
    Ne abbiamo parlato spesso: cerca parte del testo dell'errore sul forum per ottenere dei suggerimenti a riguardo.
    MARCO BREVEGLIERI
    Software and Web Developer, Teacher and Consultant

    Home | Blog | Delphi Podcast | Twitch | Altro...

  3. #3
    ok, scusa, ho trovato la soluzione con:

    codice:
            delegate void CallProgressBarStep(ProgressBar myProgressBar);
    
            private void ActuallyProgressBarStep(ProgressBar myProgressBar)
            {
                if (myProgressBar.InvokeRequired)
                {
                    CallProgressBarStep del = ActuallyProgressBarStep;
                    
                    myProgressBar.Invoke(del, new object[] { myProgressBar });
    
                    return;
                }
    
                myProgressBar.PerformStep();
            }

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.