开发者

Asynchronously execute a "heavy" method of the GUI

开发者 https://www.devze.com 2023-04-12 23:28 出处:网络
I have to do the following: Public Sub OnMouseMove If mouseDownButNotYetMoved Then myObjectsStateArchive.SaveObjectsState(myCurrentObjectsState.Clone())

I have to do the following:

Public Sub OnMouseMove

  If mouseDownButNotYetMoved Then 
    myObjectsStateArchive.SaveObjectsState(myCurrentObjectsState.Clone())
  End If    

  MoveObjectsWithMouse()

End Sub

The problem is that SaveObjectsState method is very "heavy". So, when the user moves the mouse, it expets that the object moves accordingly, but the object is "delayed", because it waits the SaveObjectsState to be finished...

I would like to probably asynchronously do the save... I mean, all the objects are in the current thread, myObjectsStateArchive and myCurrentObjectState... just the operation of cloning and saving to be "paralelized"

What would be the best method, using ThreadPool or something like this?

Public Sub OnMouseMove    
  If mouseDownButNotYetMoved Then 
    System.Threading.ThreadPool.QueueUserWorkItem( _
      New Threading.WaitCallback( _
        Sub(o)
          myObjectsStateA开发者_运维百科rchive.SaveObjectsState(myCurrentObjectsState.Clone())
        End Sub))
  End If    

  MoveObjectsWithMouse()
End Sub


You can use TaskFactory.StartNew Method available in .NET 4. From another article:

the new Task pattern in .NET 4 has built-in support for synchronization with the UI thread. This makes writing parallel applications that interact with the user interface easier than ever before.


You could use the BackgroundWorker, using a thread to achieve the task. You can show a progress bar (or any other notification way), but be care about updating the GUI from a thread, ti link maybe helpful: How to update GUI with backgroundworker?

0

精彩评论

暂无评论...
验证码 换一张
取 消