Delay until await returns a True
I have looked at many examples of Delaying a for while loop until a result is gained; but can’t come up with a solution that will not hang the system forever if the boolean variable is not attained.
I have used Thread.Sleep but it stops the await thread from returning a result. I need someone to assist me in finding a solution where the system will wait for the "LoadedShopifyProduct" to be true then continue with the "Button1.click".
*** You will see that the try variable stops once 40 is reached so I really don’t know whether the products have been loaded. Is there a better option then Thread.Sleep?
Private Sub TEST
Show()
TopMost = True
Dim HasInternet As Boolean = crm.HaveInternetConnection() :'check if there is internet
If HasInternet = False Then
Me.Close()
Exit sub
End If
Form1.LoadShopifyProducts():'calls the Async routine
Dim trys As Short = 0
While LoadedShopifyProducts = False And HasInternet = True And trys < 40
Form1.ToolStripStatusLabel1.Text = "Tries : " & trys & " -> Shopify Products Not loaded ! Please wait a few seconds"
Application.DoEvents()
Thread.Sleep(2000)
trys = trys + 1
End While
Button1.PerformClick() : 'do next
End Sub
Public Async Sub LoadShopifyProducts()
Dim HasInternet As Boolean = crm.HaveInternetConnection()
If HasInternet = True Then
TimesShopifyLoad = TimesShopifyLoad + 1
Dim BaseURL = Para(Val(TermNumber), 580)
Dim Key = Para(Val(TermNumber), 581)
Dim shopifyClient As New ShopifyApi(BaseURL, Key)
shopifyClient.Initialise()
'retrieve all Products from Shopify API
allShopifyProducts = Await shopifyClient.GetAllProducts()
'also collate a master list of all Variants from the list of Products returned above to allow searching by SKU which only appears on the variant
allShopifyVariants = Await shopifyClient.GetAllVariants(allShopifyProducts)
LoadedShopifyProducts = True :' after await set ---> to true ! !
CountShopify = allShopifyVariants.Count
ToolStripStatusLabel1.Text = "( Shopify : " & allShopifyVariants.Count & " ) Times:" & Str(TimesShopifyLoad)
End If
End Sub
2
Answers
Here’s how you would do the basic version of what you want:
If you needed to repeat the call every 2 seconds until a condition is met, then it looks like this:
Update with example timeout:
You can use a background worker and call you function from background workers do work at an event. by using a background worker you can prevent the system from hangup and also can show some progress bars before calling the background worker and hiding on completion.