How to make a very simple asynchronous method call in vb.net

前端 未结 4 1804
南方客
南方客 2020-12-30 05:17

I just have a simple vb.net website that need to call a Sub that performs a very long task that works with syncing up some directories in the filesystem (details not importa

相关标签:
4条回答
  • 2020-12-30 05:41

    This is an older thread, but I figured I'd add to it anyway as I recently needed to address this. If you want to use the ThreadPool to call a method with parameters, you can modify @Timiz0r's example as such:

    System.Threading.ThreadPool.QueueUserWorkItem(Sub() MethodName( param1, param2, ...))
    
    0 讨论(0)
  • 2020-12-30 05:43

    I also was looking for information on Asynchronous programming in VB. In addition to this thread, I also found the following: beginning with Visual Studio 2012 and .Net Framework 4.5, VB was given two new keywords to make a method asynchronous right in the declaration, without using Thread or Threadpool. The new keywords are "Async" and "Await". You may refer to the following links if you wish:

    http://msdn.microsoft.com/library/hh191443%28vs.110%29.aspx

    https://msdn.microsoft.com/en-us/library/hh191564%28v=vs.110%29.aspx

    0 讨论(0)
  • 2020-12-30 05:49

    I wouldn't recommend using the Thread class unless you need a lot more control over the thread, as creating and tearing down threads is expensive. Instead, I would recommend using a ThreadPool thread. See this for a good read.

    You can execute your method on a ThreadPool thread like this:

    System.Threading.ThreadPool.QueueUserWorkItem(AddressOf DoAsyncWork)
    

    You'll also need to change your method signature to...

    Protected Sub DoAsyncWork(state As Object) 'even if you don't use the state object
    

    Finally, also be aware that unhandled exceptions in other threads will kill IIS. See this article (old but still relevant; not sure about the solutions though since I don't reaslly use ASP.NET).

    0 讨论(0)
  • 2020-12-30 05:56

    You could do this with a simple thread:

    Add :

     Imports System.Threading
    

    And wherever you want it to run :

     Dim t As New Thread(New ThreadStart(AddressOf DoAsyncWork))
     t.Priority = Threading.ThreadPriority.Normal
     t.Start()
    

    The call to t.Start() returns immediately and the new thread runs DoAsyncWork in the background until it completes. You would have to make sure that everything in that call was thread-safe but at first glance it generally seems to be so already.

    0 讨论(0)
提交回复
热议问题