异步线程和匿名委托

时间:2010-09-20 11:34:33

标签: wpf vb.net visual-studio-2008 asynchronous anonymous-types

好的,现在我可以使用2种技术来启动我的线程:Dispatcher和BackgroundWorker。

分派器:

' I launch the asynchronous process
Dim a As New Action(AddressOf operazioneLunga)
a.BeginInvoke(Nothing, Nothing)

' I update the GUI passing some parameters
Dim a As New Action(Of Integer, String)(AddressOf aggiorna_UI)
Me.Dispatcher.BeginInvoke(DispatcherPriority.Normal, a, 5, "pippo")

BackgroundWorker的:

Private bw As BackgroundWorker = Nothing

Private Sub initial()
  bw = New BackgroundWorker
  AddHandler bw.DoWork, AddressOf longOp
  AddHandler bw.RunWorkerCompleted, AddressOf endBGW
  bw.RunWorkerAsync ()
End Sub

Private Sub longOp(ByVal sender As Object, ByVal e As DoWorkEventArgs)
  Dim l As List(Of miaClasse2) = <Long Operation ...>

  e.Result = l
End Sub

Private Sub endBGW(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs)
  Dim l As List(Of miaClasse2) = e.Result
  Dim be As BindingExpression = BindingOperations.GetBindingExpression(mioDatagrid, DataGrid.ItemsSourceProperty)
  Dim m As miaClasse1 = DirectCast(be.DataItem, miaClasse1)
  m.GetData (l)
  mioDatagrid.UpdateLayout()
  mioDatagrid.ScrollIntoView (mioDatagrid.Items(0))
  RemoveHandler bw.DoWork, AddressOf massiccia
  RemoveHandler bw.RunWorkerCompleted, AddressOf fineBGW
  bw.Dispose()
End Sub

我不知道什么是更好的,但我想我会使用BackgroundWorker,因为我认为还有其他关于Dispatcher的争论我必须知道并且我感觉不安全。

Pileggi

我以前的帖子:

大家好!

我的应用程序在WPF / Vb框架3.5 SP1中。我需要在异步线程上执行一些方法。我知道这一点:

Private Delegate Sub dMassiccia()
Private Delegate Sub dAggiornaUI()

Private Sub iniziale()
  Dim massicciaTemp As New dMassiccia(AddressOf massiccia)
  massicciaTemp.BeginInvoke(Nothing, Nothing)
End Sub

Private Sub massiccia()
  'long operations...
  Me.Dispatcher.BeginInvoke(DispatcherPriority.Normal, _
    New dAggiornaUI(AddressOf aggiornaUI))
End Sub

Private Sub aggiornaUI()
  'update the UI...
End Sub

但是这样我必须为每个我想在异步线程上启动的方法声明一个委托,这非常不舒服。我有很多方法以这种方式启动。我知道有匿名代表,但在这种情况下我不知道如何使用它们。 你能帮助我吗? Pileggi

PS。其他信息:在这一刻我不需要查找异步线程中启动的进程的状态。长操作是对Web服务的一些请求,每次都需要几秒钟。线程数没有问题,因为我限制了用户启动新线程的可能性,直到完成其中一个线程。我需要异步线程,除了其他原因,因为我不会阻止应用程序,我想用用户控件替换鼠标光标等。

1 个答案:

答案 0 :(得分:0)

你要做的是什么,需要你启动所有这些线程?看起来你正在创建辅助线程只是为了能够进行GUI更新。

首先,如果你必须创建一个 lot 的线程,那么你就有可能很快就会耗尽可用线程。我认为最大值只有64,但文档说每个进程250个,并且它也可以通过GetMaxThreadsSetMaxThreads进行设置。无论如何,您需要决定使用ThreadPool线程(使用BeginInvoke / EndInvoke时使用的线程)是否适合您。

您的GUI更新需要多长时间?他们会在整个申请期间运行吗?你可以使用常规线程吗?如果您只需要定期更新状态信息,请考虑使用BackgroundWorker进行GUI更新。在某些情况下,即使DispatcherTimer也可以做到这一点。这取决于你想做什么。

您也不会显示所有代码,但在发布的内容中,EndInvoke未被调用。如果你这样做并最终抛出异常,你将无法捕获它并正确处理错误。

相关问题