I recently started working with WinForms
via MVP (PassiveView) pattern and stuck on
"How to make View update itself while presenter does long (for like 20 seconds) async operations"
So I have a form, an IView
implementation with UI items:
- a
Button
on which my presenter is subscribed to viaClick
event; - a
DataGridView
with a checkbox column; - A
ProgressBar
; - and two fields.
Current
andSelectedCount
;
So what am I doing there?
On that Click
, my Presenter grabs "checked" items from datagrid and writes them to database.
Since that processing takes time, I made this method async
:
private async void PutToDatabase(List<Item> items)
{
View.SelectedCount = items.Count;
for (int i = 0; i < items.Count; i++)
{
await Task.Factory.StartNew(
() =>
{
// writing stuff to database via ADO.NET
View.Current = i;
});
}
}
So I am updating my Current, which updates my progressBar by doing this:
public int CurrentPrice
{
get { return _current; }
set
{
_current = value;
Invoke((MethodInvoker) delegate {progBarImportState.Value = _current; });
}
}
I'm not sure, if this approach is going to work fine, since I can't reload my UI to use the form again, unless I gonna check somwhere (e.g. in the same delegate) if progress.value == progress.maximum
and rollback the form to reuse it. Plus,
it doesn't look 'pretty'.
So are there any more effective/cleaner solution than this?