Antonio Polanco
Antonio Polanco

Reputation: 38

Invalid thread access in SWT (progressBar help)

first of all I'm sorry about my English level, I'm Spanish.

I have a little problem with a progressBar in SWT application:

  1. I have 1 Class(The application (SWT)) with all controls(progressBar, textboxes, combos, etc).
  2. I have 1 Thread class who makes a file upload to an FTP server.

My problem is, I'm getting invalid thread access when I try to update my ProgressBar.Selection(int) from my UploadThread.

I'm trying hard to solve this problem, with Timertask(I wanna upload my progressBar every second), with events (an Event fires when UploadThread stay active) but it didn't work.

I hope you can help me with this problem.

Upvotes: 1

Views: 423

Answers (2)

Tonny Madsen
Tonny Madsen

Reputation: 12718

When you use SWT, you must remember that all access to SWT objects must be performed in the SWT UI Event thread. There are a few exceptions to this, but they are typically noted in the API or rather obvious.

To make any changes to a control use the following template:

c.getDisplay().asyncExec(new Runnable() {
    @Override
    public void run() {
        if (c.isDisposed()) return;
        // ...
    }
});

This will run the Runnable object in the event thread at the soonest possible time. You can even use this construct in the event thread itself, to postpone work for later - usually to get a rapid UI response.

The if (c.isDisposed()) return; construct is here to guard against the situation where the control is disposed in the time between asyncExec(...) and run() are executed.

If you need to wait for the result to be performed, use syncExec(...) instead of asyncExec(...).

Upvotes: 1

David G
David G

Reputation: 4014

How are you creating your upload thread?

If your thread implements IRunnableWithProgress and is run by a class that implements IRunnableContext, your progress bar should be able to run in a separate thread fine.

Just specify true for the fork parameter on the run method.

The run method on IRunnableWithProgress provides an IProgressMonitor for your thread to update.

Upvotes: 0

Related Questions