|
-
Mar 6th, 2015, 11:36 PM
#2
Re: How to wait for an await method to cancel?
Hi,
I have faced a similar problem in the past and I solved this by thinking about this a bit differently. I found that trying to wait for the cancellation of a background thread could take a variable amount of time depending on the data being loaded and I always ended up duplicating data and messing up the UI similar to what you are experiencing now.
To get round this, and to let the User scroll through options as fast as they wanted to, I decided that I needed to let the Background Thread finish its current work before trying to get it to do something else. The trick here was to make sure that the UI Thread continued to keep track of what the user was doing, doing minimal work on the UI Thread, and then only processing the LAST Selected Option once the Background Thread became available again. I achieved this by adding each selected user option to a Stack and then once the Background Thread became available the LAST item on the Stack was retrieved and processed on the background thread.
Here’s a quick example using a bunch of TextBox’s on a form. Just run the cursor over the TextBox’s as quick as you want and you will see that only the last textbox is processed when the Backgoundworker becomes free. Maybe you can adapt this idea to your Carousel problem.
vb.net Code:
Public Class Form1 Private carouselStack As New Stack(Of String) Private Sub Button1_Enter(sender As Object, e As EventArgs) Handles Button1.MouseEnter, Button2.MouseEnter, _ Button3.MouseEnter, Button4.MouseEnter, Button5.MouseEnter, Button6.MouseEnter, Button7.MouseEnter carouselStack.Push(sender.name) If Not BackgroundWorker1.IsBusy Then BackgroundWorker1.RunWorkerAsync() End If End Sub Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork 'do some labour intensive work Dim lastCarouselSelection As String = carouselStack.Pop carouselStack.Clear() Label1.Invoke(Sub() Label1.Text = String.Format("Processing Button {0}", lastCarouselSelection) End Sub) Threading.Thread.Sleep(2000) End Sub Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted If carouselStack.Count > 0 Then BackgroundWorker1.RunWorkerAsync() End If End Sub End Class
Hope that helps.
Cheers,
Ian
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|