A better way to wait for a variable to change state in VB.Net

不羁岁月 提交于 2019-12-04 05:12:44

问题


I have a loop that goes through a number of values. With every value iterated, a page is loaded in a webbrowser control (with the value passed as a parameter) and when the page is loaded and read, the loop should go to the next value in the list and continue until all values are processed. I need a way to pause the procedure while the website is loading asynchronously and then resume once the page loading/reading process is complete.

The way I am doing is by using something like this, where "ReadingInProgress" is a global variable:

      ReadingInProgress = True
      wb.Navigate("http://mywebsite.com/mypage.aspx" & c)

      While ReadingInProgress
        Application.DoEvents()
      End While

The "DocumentCompleted" event of the webrowser control set "ReadingInProgress" to false which causes the while loop to exit and resume the procedure. This works, but I realize that it puts a strain on the CPU. Is there a better, less CPU intensive way to do this?

Thanks!


回答1:


I've recently answered a similar question. The solution is in C#, but you can use Async/Await in VB.NET in a very similar way. Using this technique, you would get a natural flow of execution for your code (DocumentComplete event is encapsulated as Task).




回答2:


One way would be to take whatever is after the loop, and put that in the handler for the control's DocumentComplete event.

Another would be to have this code run in another thread. It'd start the navigation and then wait on a semaphore, EventWaitHandle, or other waitable object that the DocumentComplete handler sets. Something like this:

private sem as Semaphore
private withevents wb as WebBrowser

...

sub DoWork()
    for each url as String in urls
        ' You'll almost certainly need to do this, since this isn't the UI thread
        ' anymore.
        wb.invoke(sub() wb.Navigate(url))
        sem.WaitOne()

        ' wb is done

    next
end sub

sub wb_DocumentComplete(sender as obj, args as WebBrowserDocumentCompletedEventArgs) _
handles wb.DocumentCompleted
    sem.Release()
end sub

...

dim th as new Thread(addressof me.DoWork)
th.Start()

Either way, since you're not taking up the UI thread anymore, you don't have to worry about Application.DoEvents().



来源:https://stackoverflow.com/questions/18316009/a-better-way-to-wait-for-a-variable-to-change-state-in-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!