Скорость отклика WinForms UI при контакте с “тяжелыми” данными

Поскольку Вы, конечно, обнаружили, копирование к целевому каталогу, который уже существует , не будет работать:

svn cp svn://my_project/vendor/1.1 svn://my_project/trunk

, потому что соединительная линия уже существует, таким образом, Вы закончили бы с:

svn://my_project/trunk/1.1

Используя [1 117] слияние имеет неудачное свойство не хранения истории поставщика 1,1 тега в подрывной деятельности до 1,5, который представил отслеживание слияния. Вы не можете заботиться. В этом случае слияние было бы правильным решением:

svn co svn://my_project/trunk trunk-wc
svn merge svn://my_project/trunk svn://my_project/vendor/1.1 trunk-wc

лучший способ считать это слияние: Сначала определите изменения, необходимые для сделать trunk идентичный vendor/1.1, затем применить те изменения в данной рабочей копии (также соединительной линии, в этом случае).

я должен указать, что это слияние эффективно сдует что-либо, что было в соединительной линии ранее. Так, если Вы будете иметь локальный (непоставщик) модификации уже на соединительной линии, Вы захотите применить просто изменения между 1,1 и предыдущее отбрасывание поставщика:

svn co svn://my_project/trunk trunk-wc
svn merge svn://my_project/vendor/1.0 svn://my_prjoect/vendor/1.1 trunk-wc

, Если соединительная линия существует, но пуста , у Вас есть два варианта: замените соединительную линию или запишите немного цикла оболочки:

Замена соединительной линии похожа на это:

svn rm svn://my_project/trunk
svn cp svn://my_project/vendor/1.1 svn://my_project/trunk

Усиление оболочки (удар):

svn co svn://my_project/trunk trunk
svn co svn://my_project/vendor/1.1 1.1
( cd 1.1
  for x in * ; do
    svn cp $x ../trunk
  done 
)
svn ci trunk
5
задан Sean Hanley 5 November 2009 в 19:18
поделиться

3 ответа

The retrieval can, and should, be pushed off to a background thread--but there's some patterns to put it all in place.

Basically you'll start a background thread to retrieve the data, once it's done it will need to merge back into the UI thread to do the actual UI updates (UI updates across threads are bad bad bad).

There's three basic ways of background threading for you to explore

  • the easiest/most limited (and quirky IMO) is the BackgroundWorker component
  • using Delegates and their BeginInvoke()/EndInvoke() methods provide a nice balance of ease and flexibility (and use ThreadPool Threads)
  • using raw Thread objects provides the most control, but are slower to setup than ThreadPool Threads

Personally I lean towards the Delegates option; they're pretty easy to work with once you get the pattern down. The BackgroundWorker seems nice up front but has some gotchas and missing plumbing that make it more cumbersome to work with than you'd expect. Let me whip up a short sample of the Delegate approach; I'll update shortly...

edit

Here's some code, it's in VB but should be easy enough to transcribe if you're a C# guy. You have a couple more options on how you want the background thread to behave, so there's two samples here. Non-blocking is my prefered, but if you're fitting it into existing code then blocking might be easier for you.

Non-blocking, the callback method (GetData_Complete) will be called on the UI thread once the background thread is complete

Sub Main()

    Console.WriteLine("On the main thread")
    Dim dataDelegate As New GetDataCaller(AddressOf GetData)

    Dim iar As IAsyncResult

    ' Non-blocking approach using a callback method
    iar = dataDelegate.BeginInvoke(AddressOf GetData_Complete, Nothing)

End Sub

Private Delegate Sub GetData_CompleteCaller(ByVal iar As IAsyncResult)
Private Sub GetData_Complete(ByVal iar As IAsyncResult)
    If InvokeRequired Then
        Dim invokeDelegate As New GetData_CompleteCaller(AddressOf GetData_Complete)
        Invoke(invokeDelegate, New Object() {iar})
        Exit Sub
    End If

    ' Downcast the IAsyncResult to an AsyncResult -- it's safe and provides extra methods
    Dim ar As System.Runtime.Remoting.Messaging.AsyncResult = DirectCast(iar, System.Runtime.Remoting.Messaging.AsyncResult)

    Dim dataDelegate As GetDataCaller = DirectCast(ar.AsyncDelegate, GetDataCaller)
    Dim result As String = dataDelegate.EndInvoke(iar)

    Console.WriteLine("On the main thread again, background result is: " + result)

End Sub

Private Delegate Function GetDataCaller() As String
Private Function GetData() As String
    Console.WriteLine("On the background thread!")

    For index As Integer = 0 To 2
        Console.WriteLine("Background thread is working")
    Next

    Return "Yay, background thread got the data!"

End Function

Blocking Sub Main ()

    Console.WriteLine("On the main thread")
    Dim dataDelegate As New GetDataCaller(AddressOf GetData)

    Dim iar As IAsyncResult

    ' blocking approach; WaitOne() will block this thread from proceeding until the background thread is finished
    iar = dataDelegate.BeginInvoke(Nothing, Nothing)
    iar.AsyncWaitHandle.WaitOne()
    Dim result As String = dataDelegate.EndInvoke(iar)
    Console.WriteLine("On the main thread again, background result is: " + result)

End Sub

Private Sub GetData_Complete(ByVal iar As IAsyncResult)

    ' Downcast the IAsyncResult to an AsyncResult -- it's safe and provides extra methods
    Dim ar As System.Runtime.Remoting.Messaging.AsyncResult = DirectCast(iar, System.Runtime.Remoting.Messaging.AsyncResult)

    Dim dataDelegate As GetDataCaller = DirectCast(ar.AsyncDelegate, GetDataCaller)
    Dim result As String = dataDelegate.EndInvoke(iar)

    Console.WriteLine("On the main thread again, background result is: " + result)

End Sub

Private Delegate Function GetDataCaller() As String
Private Function GetData() As String
    Console.WriteLine("On the background thread!")

    For index As Integer = 0 To 2
        Console.WriteLine("Background thread is working")
    Next

    Return "Yay, background thread got the data!"

End Function
6
ответ дан 14 December 2019 в 08:58
поделиться

Никогда не обновляйте пользовательский интерфейс из какого-либо фонового потока, после того как вы загрузили данные со своего сервера, вызовите их обратно в поток пользовательского интерфейса для обновления элементов управления пользовательского интерфейса или набора данных, к которым привязан ваш пользовательский интерфейс.

Использование BackgroundWorker поможет в этом случае просто подключить события.

HTH

Phil '

1
ответ дан 14 December 2019 в 08:58
поделиться

Loading (as in "retrieving from data source") might be trivial, whether you use delegates, background workers or any other protocol. But binding seems tricky, because there's not much control one can exert over it, at least in most data-bound controls - you may retrieve data asynchronously, but once you have it ready how to feed it to a large grid in the background? Is that your question? If so, I think you may either:

  • create (or subclass) your view control, providing interfaces for asynchronous load;
  • implement a paged view, showing only N records at a time, so that the UI isn't blocked while fetching/formatting records.
0
ответ дан 14 December 2019 в 08:58
поделиться
Другие вопросы по тегам:

Похожие вопросы: