C #: populating user interface using separate threads

I am trying to make some sense out of an application that was passed in to track the source of the error. Theres a bit of code (simplified here) that creates four threads, which in turn populate the list view in the main form. Each method receives data from the database and extracts the graphic from the resource DLL to directly fill the mailing list.

From what Ive read here ( link ), updating user interface elements from any thread other than a user interface thread should not be performed, and yet it works?

Thread t0 = new Thread(new ThreadStart(PopulateListView1));
t0.IsBackground = true;
t0.Start();

Thread t1 = new Thread(new ThreadStart(PopulateListView2));
t1.Start();

Thread t2 = new Thread(new ThreadStart(PopulateListView3));
t2.Start();

Thread t3 = new Thread(new ThreadStart(PopulateListView4));
t3.Start();

- System.InvalidOperationException. " ImageList". , - .

, , ?

Update:

, , "". Windows, - . , . .. .

+3
5

, DoWork() BackgroundWorker class, , . , (InvokeRequired ), , .

private delegate IList<MyObject> PopulateUiControl();

private void myThread_DoWork(object sender, DoWorkEventArgs e) {
    PopulateUiControl myDelegate = FillUiControl;

    while(uiControl.InvokeRequired)
        uiControl.Invoke(myDelegate);
}

private IList<MyObject> FillUiControl() {
    uiControl.Items = myThreadResultsITems;
}

, .., .

, , , - . ,.NET 4 , Microsoft , parallelism .

+3
  • - , WOrkItems THreadPool. - ThreadPool API .NET 4.0 .

  • . "" , .net , .

+6

. , undefined. :

Control.CheckForIllegalCrossThreadCalls = true;

After that, each unsuccessful attempt to update the user interface fails, which allows you to fix all errors in the code.

+2
source

If this is done because it takes time to get the values ​​of fr listviews, then get the values ​​in the working document, and then use the main thread to bind the data to the list.

0
source

Source: https://habr.com/ru/post/1744763/


All Articles