dotNET
dotNET

Reputation: 35400

WPF: Wait animation window blocks

I have seen several similar questions on SO and elsewhere, but none seems to work for me.

I have a small Window in my project containing a LoadingAnimation that I show up at application startup and want to keep actual processing running. Here's my startup code:

Dim WaitWindow As New WaitWindow("Loading application...")
WaitWindow.Show()
LongRunningLoading()
WaitWindow.Close()

Here's LongRunningLoading() function that I try to run on a separate thread to avoid blocking my animation:

Private Function LongRunningLoading() As Boolean
    Dim resetEvent As New System.Threading.ManualResetEvent(False)

    Dim RetVal As Boolean = False
    ThreadPool.QueueUserWorkItem(Sub(state)
                                    'DO SOMETHING AND RETURN RESULTS
                                    resetEvent.Set()
                                 End Sub,
                                 RetVal)

    resetEvent.WaitOne()
    Return RetVal
End Function

Everything works as expected except that the loading animation doesn't play. What am I doing wrong?

Upvotes: 0

Views: 865

Answers (3)

dotNET
dotNET

Reputation: 35400

This approach worked for me:

   Dim waitwindow As New WaitWindow("Loading application...")

   ThreadPool.QueueUserWorkItem( _
        Sub()
            LongRunningLoading()
            Dispatcher.Invoke(New Action(AddressOf waitwindow.Close))
        End Sub)

    waitwindow.ShowDialog()

May help someone else.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500645

What am I doing wrong?

You're doing this:

resetEvent.WaitOne()

That blocks the UI thread. Don't do that. Instead, remember that the UI is basically event based - unless you're using the async features in VB 11, you'll have to write your code in an event-based way. So basically when your long-running task completes, you need to post back to the UI thread to execute the WaitWindow.Close() part.

If you can use .NET 4.5 and VB 11, you can use Task.Run to start a new task for your long-running work, and then Await that task from an asynchronous method.

Upvotes: 1

scetiner
scetiner

Reputation: 361

They are both running on UI Thread, this is why loading animation is waiting. Try to use BackgroundWorker for your LongRunningLoading process and then return to UI thread if needed for your results.

Upvotes: 0

Related Questions