2011-07-05 7 views
1

웹 서버의 데이터에 액세스하는 webserver.while에서 C# 및 데이터베이스를 사용하여 응용 프로그램을 만들고 있는데, 매우 느리고 폼이 또한 데이터가로드 될 때까지 중단됩니다. 먼저 양식을로드하고 나중에 데이터를로드하는 방법은 무엇입니까?데이터 독립적 인 UI로드 방법

답변

3

일반적인 문제 해결 방법은 BackgroundWorker 클래스를 사용하는 것입니다.

public void InitBackgroundWorker() 
{ 
    backgroundWorker.DoWork += YourLongRunningMethod; 
    backgroundWorker.RunWorkerCompleted += UpdateTheWholeUi; 

    backgroundWorker.WorkerSupportsCancellation = true; // optional 

    // these are also optional 
    backgroundWorker.WorkerReportsProgress = true; 
    backgroundWorker.ProgressChanged += UpdateProgressBar; 
} 

// This could be in a button click, or simply on form load 
if (!backgroundWorker.IsBusy) 
{ 
    backgroundWorker.RunWorkerAsync(); // Start doing work on background thread 
} 

// ... 

private void YourLongRunningMethod(object sender, DoWorkEventArgs e) 
{ 
    var worker = sender as BackgroundWorker; 

    if(worker != null) 
    { 
     // Do work here... 
     // possibly in a loop (easier to do checks below if you do) 

     // Optionally check (while doing work): 
     if (worker.CancellationPending == true) 
     { 
      e.Cancel = true; 
      break; // If you were in a loop, you could break out of it here... 
     } 
     else 
     { 
      // Optionally update 
      worker.ReportProgress(somePercentageAsInt); 
     } 

     e.Result = resultFromCalculations; // Supports any object type... 
    } 
} 

private void UpdateProgressBar(object sender, ProgressChangedEventArgs e) 
{ 
    int percent = e.ProgressPercentage; 
    // Todo: Update UI 
} 

private void UpdateTheWholeUi(object sender, RunWorkerCompletedEventArgs e) 
{ 
    if (e.Cancelled) 
    { 
     // Todo: Update UI 
    } 
    else if (e.Error != null) 
    { 
     string errorMessage = e.Error.Message; 
     // Todo: Update UI 
    } 
    else 
    { 
     object result = e.Result; 
     // Todo: Cast the result to the correct object type, 
     //  and update the UI 
    } 
} 
+0

닷넷 4, 당신은 또한 [TPL'Task' 클래스 (http://stackoverflow.com/questions/3513432/task-parallel-library-replacement-for-backgroundworker을 체크 아웃 할 수 있습니다) –

2

멀티 스레딩에 대해 알고 싶습니다. 예를 들어 thisthis을 참조하십시오.

1

UI thread에없는 thread의 데이터를 가져올 수 있습니다. 이렇게하면 UI가 멈추지 않습니다. 이 게시물에서 threading에 대해 설명해주십시오. 컨트롤을 만든 스레드가 아닌 스레드에서 컨트롤을 업데이트 할 수 없습니다. 이를 해결하려면 post을 살펴보십시오.

1

어떤 종류의 데이터를 사용하십니까? 멀티 스레딩은 당신을 위해 어려운 경우

2

을 당신은 BackgroundWorker에를 사용하거나 (당신이 webservivce를 호출 할 경우) 어떤 경우에는 비동기 방법이 있습니다, 당신은 처음에 데이터의 일부를로드 할 수 있습니다 양식에 단추를 넣어 사용자가 다른 부분의 데이터를 가져올 수있게하십시오. 일반적으로 주문형 로딩이라고하며 페이징이라고 불리는 방식으로 구현됩니다. 10000 개의 정보 기록이 있다고 상상해보십시오. 처음 100 개의 레코드를로드 한 다음 원하는 경우에만 두 번째 100 개의 레코드를로드 할 수 있습니다. 서버에서 오랜 시간 작업을하고 문제가 주문형 로딩이 아니라면 스레딩을 사용하는 것이 유일한 방법입니다.

관련 문제