How to execute a function called many times, only once!

Is there a way to execute a function called a thousand times just once? I have a function that adds items to the sort container, and there is code that updates lists and other windows (GUI employees). So, if I need to add a million elements (the number of which is impossible to say, anyone can call the function from anywhere), the GUI update mechanism will be called as many times ... Is there a way to tell appart to continuously execute the function (and ignore it) from intermittent ? Is there a safe way to execute the update mechanism only the last time the add-item function is called during the time interval?

Thank.

+3
source share
8 answers

Roesone, your code is broken. He resists your attempts to write it, because he knows that it is wrong. You can probably find some kind of grungy hack that will emit your behavior. But this decision will be a hack; fragile, error prone and difficult to maintain. And especially vulnerable to ripple effects. As soon as you make a small change in your code somewhere in something that touches this functionality remotely, the grungy hack will break and you will be worse than it is now.

, , , . , . . , , . . , , - .

, .

+11

static bool, , true, .

+6

, "" ( ) , ?

// add one item:
window.add_item()

// add many items:
window.set_redraw(false)
window.add_many_items()
window.set_redraw(true)

add_item GUI. .

+2

, .

+1

API Win32, SetTimer, . SetTimer , TimerID , , reset. , SetTimer , , , "n" .

  UINT_PTR timerID = SetTimer(NULL, someUniqueID, 1000, yourCallback);

KillTimer .

MSDN SetTimer

0

, ( , !). , , , .

, , , , . , ( , ), , .

, , , .

0

(IMHO) - , .NET :

- SuspendLayout, , . "ResumeLayout", .

, , - , , , .

, , .. . SuspendLayout, , (SuspendLayout (int forNumberOfItems)), .

0

, .

, :

bool g_isValueModified = false ;
Value g_value ;

void setValue(Value value)
{
   g_value = value ;
   g_isValueModified = true ;
}

void updateValueOnGUI()
{
   if(g_isValueModified)
   {
      g_isValueModified = false ;

      // put here the code to set the value in the GUI widget
   }
}

setValue , updateValueOnGUI , , 10 100 .

:

  • raw Win32, Win32 WinProc
  • in the extended GUI infrastructure, use a timer
  • or in the advanced GUI infrastructure, use two separate threads: one for executing the code (using the set method) and one for executing the GUI (performing the update), making sure that g_value and g_isValueModified are written / read in multithreaded mode (for example, locks, critical sections etc.).
0
source

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


All Articles