set priority for Parallel.For loop

前端 未结 5 1646
半阙折子戏
半阙折子戏 2021-01-05 16:21

Ok, here\'s the situation: My main/UI thread (call it Thread1) is used for acquiring a batch of images from a phsycial document scanner. When a batch has been acquired, a se

5条回答
  •  我在风中等你
    2021-01-05 16:55

    Without access to the entire application it is difficult to know exactly what is happening here but let's start by breaking down Parallel.For:

    private void ThreadWork(object data) // executing in Thread2
    {
        // Thread2 running here
        SaveContainer sc = data as SaveContainer; // holds images
    
        bool[] blankIndex = new bool[sc.imagelist.Count]; // to use in Parallel.For loop
        for (int i = 0; i < sc.imagelist.Count; i++)
            blankIndex[i] = false; // set default value to false (not blank)
    
        // Thread2 blocks on this call
        Paralle.For(0, sc.imagelist.Count, i => // loop to mark blank images
        {
            // Thread from the pool is running here (NOT Thread2)!!!
    
            bool x = false; // local vars make loop more efficient
            x = sc.IsBlankImage((short)i); // check if image at index i is blank
            blankIndex[i] = x; // set if image is blank
        }
        // Thread2 resumes running here
    
        .... // other image processing steps
    }
    

    So changing Thread2's priority will not make a difference since it is blocked anyway. However, if Thread1 is not blocked, it should still be able to run. Thread1 may not run often, which could be your problem.

    The naive approach would be to do something like mess with thread priorities, counts, or add some Thread.Yield() statements. However, the threads from the pool are likely already blocking since they are doing I/O.

    Most likely, what you need to do here is refactor your code so that your image loading loop blocks on your main thread's image acquiring using something like System.Threading.WaitHandle or move more of the work the main thread is doing into the image loading. Without refactoring, experience says you will end up with a solution that is tailored to the specific machine you are testing on, under specific running conditions but, when loads change or hardware changes, your "tuning" will be off.

    Rework the code so more work is being done inside your Parallel.For workers and block your threads on main thread activity when there is work for the main thread and you will have a solution of which you are proud.

提交回复
热议问题