나는 내 응용 프로그램에 다음 코드가 있습니다업데이트 UI C#에서 타이머를 사용하여 1 초마다
이Task.Factory.StartNew(() =>
{
progressReporter.ReportProgress(() =>
{
stopWatch.Start();
lblStatus.Text = "We've begun!";
});
int c = 0;
DateTime starttime = DateTime.Now;
foreach (string file in fileList)
{
c++;
csvCreator.createCSV(file);
progressReporter.ReportProgress(() =>
{
//Estimated time remaining
if (c % 100 == 0)
{
TimeSpan timespent = DateTime.Now - starttime;
int secondsremaining = (int)(timespent.TotalSeconds/c * (total - c));
TimeSpan t = TimeSpan.FromSeconds(secondsremaining);
lblTimeRemaining.Text = string.Format("{0:D2}h:{1:D2}m:{2:D2}s",
t.Hours,
t.Minutes,
t.Seconds,
t.Milliseconds);
}
//Progress bar
int percentComplete = (c * 100/total);
if ((int)percentComplete <= progressBar.Maximum)
{
progressBar.Value = (int)percentComplete;
}
}
});
}
지금, 내 코드의 모든 100 반복 확인하고는 UI를 업데이트합니다. 더 나은 사용자 환경을 제공하기 위해 매초마다 확인하는 것이 좋습니다.
어떻게하면 좋을지 아이디어가 있습니까?
를 사용하여 UI 그것을 틱마다 업데이트 할 수 있습니다. 당신은 이미 그 해결책을 알고 있습니다. 하지만 실제 문제는 아마도 주 스레드에서 시간이 많이 걸리는 작업 일 것입니다. 백그라운드 스레드에서 UI 업데이트가 필요하며 UI 스레드로 UI 업데이트를 호출해야합니다. –
감사합니다. 내 기존 코드 컨텍스트에서 Timer 개체를 사용하여 특정 구현을 찾고 있어요. createCSV는 프로세서 집약적 인 작업이지만 실제로 백그라운드 스레드에서 실행되며 ProgressReporter 클래스를 사용하면 UI 스레드를 액세스하여 UI를 업데이트하여 멋지고 신선한 상태로 유지할 수 있습니다. –
그냥 타이머를 만들고 속성을 설정하고 이벤트 처리기를 추가하면 좋은 결과를 얻을 수 있습니다. 그게 전부입니다. –