WPF: releasing an interface update from a background thread

My code starts a background thread. The background thread makes changes and wants the user interface in the main thread to be updated. The code that starts the stream then waits for something like this:

                Thread fThread = new Thread(new ThreadStart(PerformSync));

                fThread.IsBackground = true;
                fThread.Start();

                fThread.Join();

                MessageBox.Show("Synchronization complete");

When the background wants to update the user interface, it installs StatusMessage and calls the code below:

    static StatusMessage _statusMessage;
    public delegate void AddStatusDelegate();
    private void AddStatus()
    {
        AddStatusDelegate methodForUIThread = delegate
        {
            _statusMessageList.Add(_statusMessage);
        };

        this.Dispatcher.BeginInvoke(methodForUIThread, System.Windows.Threading.DispatcherPriority.Send);
    }

_statusMessageList is an ObservableCollection that is the source of the ListBox.

The AddStatus method is called, but the code in the main thread is never executed - that is, _statusMessage is not added to the _statusMessageList during the execution of the stream. However, as soon as it is completed (fThread.Join () returns), all related calls in the main thread are executed.

fThread.Start() fThread.Join(), .

, ( ) ?

.

+3
3

fThread.Join , . , .

, - (, ):

void someUiEventThatCausesTheBackgroundProcessingToStart() {
    Thread fThread = new Thread(new ThreadStart(PerformSync));
    fThread.IsBackground = true;

    // disable some UI components here, so that the user cannot
    // start the thread a second time
    ...

    fThread.Start();

    // *don't* call Thread.Join here, so that your main thread does not block!
}

void PerformSync() {
    try {
        // do your stuff here
        ...
    } finally {
        Dispatcher.Invoke(new Action(ProcessingDone));
    }
}

void ProcessingDone() {
    // re-enable the UI components
    ...

    MessageBox.Show("Synchronization complete");
}

, WPF / IsBusyProcessing, , ...

EDIT: BackgroundWorker, ProgressChanged RunWorkerCompleted, .

+6
fThread.IsBackground = true;
fThread.Start();

fThread.Join();

Join() , . , , . Join(). - , .

EDIT: , , Start Join, , Join.

+4

BackgroundWorker - . , , , (, ) , .

+1
source

Source: https://habr.com/ru/post/1746038/


All Articles