3

Possible Duplicate:
Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on

How to correct this exception :

Cross-thread operation not valid: Control 'pgImportProcess(ProgressBar control)' accessed from a thread other than the thread it was created on.

Code :

Form :

private void btnImport_Click(object sender, EventArgs e)
{

        if (CheckDataValidation() == false) return;

        if (MessageBox.Show("Do you want to import this file?", "Import", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) return;
        Cursor.Current = Cursors.WaitCursor;
        //_blacklist.Process(pgImportProcess);

        Thread thread = new Thread(new ThreadStart(delegate { _blacklist.Process(pgImportProcess); }));
        thread.Start();

        if (!thread.IsAlive) thread.Abort();

        //ThreadStart process = delegate
        //                                {
        //                                    _blacklist.Process(pgImportProcess);
        //                                };
        //Thread threadProcess = new Thread(process);
        //threadProcess.Start();

        //if(!threadProcess.IsAlive) threadProcess.Abort();

    }

Class :

public void Process(ProgressBar process)
{

        int same = 0, added = 0, updated = 0;

        OracleConnection connection = (OracleConnection)DbConnection.Instance();
        OracleTransaction transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted);

        process.Step = 1;
        process.Minimum = 1;
        process.Maximum = _recordNumber;



        while (_csv.ReadNextRecord())
        {
            if (_csv[0] == null | _csv[0] == "") break;

            process.PerformStep();

            using (OracleCommand cmd = new OracleCommand(_sql, connection))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandTimeout = 600;
                cmd.BindByName = true;

                switch (_fieldCount)
                {
                    case SdnName :
                        ImportBlacklistName(cmd);
                        break;
                    case SdnAddress:
                        ImportBlacklistAddress(cmd);
                        break;
                    case SdnAlt :
                        ImportBlacklistAlt(cmd);
                        break;
                }

                try
                {
                    cmd.ExecuteNonQuery();


                    switch (cmd.Parameters["message_out"].Value.ToString())
                    {
                        case "Added":
                            added += 1;
                            break;
                        case "Same":
                            same += 1;
                            break;
                        case "Updated":
                            updated += 1;
                            break;
                    }
                }
                catch (Exception error)
                {
                    transaction.Rollback();
                    MessageBox.Show(error.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
        transaction.Commit();
        MessageBox.Show(String.Format("Total Record : {0} ; Added : {1} ; Updated : {2} ; Same : {3} !!!!",_recordNumber,added,updated,same), "Import successsfull", MessageBoxButtons.OK, MessageBoxIcon.Information);
        _recordNumber = 0;
        process.Value = 1;
        _csv.Dispose();
    }

it catches an exception at the time of Process.step = 1

How to solve this problem ? Thank in advance

Community
  • 1
  • 1
Oudam San
  • 77
  • 1
  • 10
  • Please look for related questions when attempting to post a new question. Then you would have discovered some of these questions: [1](http://stackoverflow.com/questions/142003/cross-thread-operation-not-valid-control-accessed-from-a-thread-other-than-the), [2](http://stackoverflow.com/questions/5037470/cross-thread-operation-not-valid), [3](http://stackoverflow.com/questions/4010602/c-sharp-cross-thread-operation-not-valid) – Matthias Dec 20 '11 at 03:54

3 Answers3

3

You can't update the user interface from a different thread (as the error states).

You need to Invoke the method. Any easy way to do this is through the MethodInvoker:

        process.Parent.Invoke((MethodInvoker)delegate
        {
            process.Step = 1;
            process.Minimum = 1;
            process.Maximum = _recordNumber;
        });

You will need to use this code anytime you try to update properties in your progress bar.

competent_tech
  • 44,465
  • 11
  • 90
  • 113
2

you need to use BeginInvoke with a delegate such as:

MethodInvoker yourAction = delegate
     { process.Step = 1;
    process.Minimum = 1;
    process.Maximum = _recordNumber; };
process.BeginInvoke(yourAction);
Tom
  • 539
  • 4
  • 7
1

You need to use Dispatcher to get into UI's thread.

If you use WPF:

Dispatcher.BeginInvoke(new Action(()=>
{
    //place code here
}));
Artem Makarov
  • 874
  • 3
  • 14
  • 25