タイマが呼び出されるたびにUpdateDocumentsListFromServer
UIが3秒間フリーズします。 .net 3.5で非同期スタイルのリストを更新するには?DispatcherTimer WPF async
のViewModel:
public class ShippingDocumentsRegisterViewModel : ViewModelBase
{
ShippingDocumentsModel model = new ShippingDocumentsModel();
DispatcherTimer timer = new DispatcherTimer();
BackgroundWorker BW = new BackgroundWorker();
public ShippingDocumentsRegisterViewModel()
{
timer = new DispatcherTimer();
timer.Tick += new EventHandler(UpdateDocumentsListFromServer);
timer.Interval = new TimeSpan(0, 0, 10);
timer.Start();
this.Columns = model.InitializeColumns();
BW.DoWork += UpdateDocumentsList;
BW.RunWorkerAsync();
}
public void UpdateDocumentsList(object o, EventArgs args)
{
this.ShippingDocuments = model.GetDocuments();
}
public void UpdateDocumentsListFromServer(object o, EventArgs args)
{
// Taking a lot of time. How to do it async?
var tempDocuments = model.GetDocumentsFromServer();
foreach (var item in tempDocuments)
{
this.shippingDocuments.Add(item);
}
//
}
private ObservableCollection<ShippingDocument> shippingDocuments;
public ObservableCollection<ShippingDocument> ShippingDocuments
{
get
{
return shippingDocuments;
}
private set
{
shippingDocuments = value;
RaisePropertyChanged("ShippingDocuments");
}
}
public ObservableCollection<ShippingDocumentColumDescriptor> Columns { get; private set; }
}
GetDocumentsFromServerが
public ObservableCollection<ShippingDocument> GetDocumentsFromServer()
{
System.Threading.Thread.Sleep(3000);
return new ObservableCollection<ShippingDocument> { new ShippingDocument { Name = "Test" } };
}
'Sleep(3000)'があるのでフリーズします。おそらく、あなたはバインディング[IsAsync](https://msdn.microsoft.com/en-us/library/system.windows.data.binding.isasync(v = vs.110).aspx)を設定したいと思うでしょう不動産になる)?もう一つの*オプションは 'GetDocumentsFromServer'を' async'として定義し、内部で非同期メソッドを使うことです( '' await Task.Delay() 'や' 'Task.Run(()=> Thread.Sleep())を待ちます。願い)。 – Sinatr
@Sinatr、はい私はSleep(3000)freez UIを知っています。それは長時間の作業をエミュレートします。 .net 3.5では、非同期のメソッドはありません。 – A191919
私は[DispactherTimer]の代わりに[Timer](https://msdn.microsoft.com/en-us/library/zdzx8wx8.aspx)に行くことをお勧めします。 'DispactherTimer'は、' Timer'がスレッドプールからスレッドを使用するUIThreadにアクセスします。 – Gopichandar