Page 1 of 2 12 LastLast
Results 1 to 40 of 53

Thread: Complied app hangs on Exit Function statement

  1. #1

    Thread Starter
    Lively Member
    Join Date
    May 2018
    Location
    Russia
    Posts
    66

    Question Complied app hangs on Exit Function statement

    Hello, everybody!

    My programm process a lot of data (accounting) using DAO 3.6. All works fine in IDE and when I compile it to P-code. The issue appears only when I compile app to Native Code (without any Advanced optimizations).

    Code flow:
    ========
    Visual Basic Code:
    1. Sub subPARENT()
    2.    With RS
    3.       Do Until .EOF
    4.          nRecord = nRecord + 1        
    5.          'The program hangs on the same nRecord=3562 every time,
    6.          'but the record is absolutely usual.
    7.          bSuccess = funcCHILD()
    8.          .MoveNext
    9.       Loop
    10.    End With
    11. End Sub
    12.  
    13. Function funcCHILD() as Boolean
    14.    Dim bRetval as Boolean
    15.    'A lot of stuff here  
    16.    funcCHILD = bRetval
    17.    Exit Function 'The app hangs here
    18. End Function

    Enviroment:
    =========
    VB6 Professional
    Windows XP SP3
    DAO 3.6

  2. #2
    PowerPoster Zvoni's Avatar
    Join Date
    Sep 2012
    Location
    To the moon and then left
    Posts
    2,725

    Re: Complied app hangs on Exit Function statement

    Then remove Line 17
    An "Exit Function" directly before an "End Function" is like shooting dead people in the head: It's messy, and has no effect
    One System to rule them all, One Code to find them,
    One IDE to bring them all, and to the Framework bind them,
    in the Land of Redmond, where the Windows lie
    ---------------------------------------------------------------------------------
    People call me crazy because i'm jumping out of perfectly fine airplanes.
    ---------------------------------------------------------------------------------
    Code is like a joke: If you have to explain it, it's bad

  3. #3

    Thread Starter
    Lively Member
    Join Date
    May 2018
    Location
    Russia
    Posts
    66

    Re: Complied app hangs on Exit Function statement

    Quote Originally Posted by Zvoni View Post
    Then remove Line 17
    An "Exit Function" directly before an "End Function" is like shooting dead people in the head: It's messy, and has no effect
    Of course, this is not the full code. There is an error handler below.

  4. #4
    PowerPoster wqweto's Avatar
    Join Date
    May 2011
    Posts
    3,437

    Re: Complied app hangs on Exit Function statement

    In IDE break on Exit Function and press F8 (Step Into) to observe all the Class_Terminate called when local objects are getting out of scope.

    cheers,
    </wqw>

  5. #5

    Thread Starter
    Lively Member
    Join Date
    May 2018
    Location
    Russia
    Posts
    66

    Re: Complied app hangs on Exit Function statement

    Quote Originally Posted by wqweto View Post
    In IDE break on Exit Function and press F8 (Step Into) to observe all the Class_Terminate called when local objects are getting out of scope.
    This happens in the .bas module

  6. #6
    PowerPoster Zvoni's Avatar
    Join Date
    Sep 2012
    Location
    To the moon and then left
    Posts
    2,725

    Re: Complied app hangs on Exit Function statement

    He mentioned an Error-Handler, my money is on the Error-Handler, since somewhere must be an "On Error Goto" or an OERN

    I misplaced my crystal ball, and since this is not the whole code, i'm out of this thread.
    One System to rule them all, One Code to find them,
    One IDE to bring them all, and to the Framework bind them,
    in the Land of Redmond, where the Windows lie
    ---------------------------------------------------------------------------------
    People call me crazy because i'm jumping out of perfectly fine airplanes.
    ---------------------------------------------------------------------------------
    Code is like a joke: If you have to explain it, it's bad

  7. #7
    PowerPoster wqweto's Avatar
    Join Date
    May 2011
    Posts
    3,437

    Re: Complied app hangs on Exit Function statement

    Quote Originally Posted by Nouyana View Post
    This happens in the .bas module
    Suppose you have this routine in a .bas module

    Code:
    Function funcCHILD() as Boolean
        Dim o As MyBusinessObject
        Set o = New MyBusinessObject
        'A lot of stuff here   
        funcCHILD = bRetval
        Exit Function 'Class_Terminate for MyBusinessObject class fired here for local variable o
    End Function
    Objects do get terminated when local variables (being last reference) are going out of scope upon exiting the routine.

    You can put explicit Set o = Nothing just before Exit Function statement so to be able to pinpoint which Class_Terminate hangs exactly.

    cheers,
    </wqw>

  8. #8

    Thread Starter
    Lively Member
    Join Date
    May 2018
    Location
    Russia
    Posts
    66

    Re: Complied app hangs on Exit Function statement

    Quote Originally Posted by wqweto View Post
    Suppose you have this routine in a .bas module

    Code:
    Function funcCHILD() as Boolean
        Dim o As MyBusinessObject
        Set o = New MyBusinessObject
    End Function
    No, I haven't. All objects I use in subPARENT and funcCHILD were defined earlier.

  9. #9
    PowerPoster
    Join Date
    Feb 2017
    Posts
    3,527

    Re: Complied app hangs on Exit Function statement

    Quote Originally Posted by Nouyana View Post
    No, I haven't. All objects I use in subPARENT and funcCHILD were defined earlier.
    But can't you do what wqweto suggested anyway to ensure that there is no code (from your program) executing upon exiting the procedure?
    Discarding something without actually testing is not a good debugging practice.

    On the other side, if the bug is not in your code, then it is obviously in a third party component (or may be VB6 itself, although unlikely).

    That means that in your code the problem is in:

    Quote Originally Posted by Nouyana View Post
    Code:
    'A lot of stuff here

  10. #10

    Thread Starter
    Lively Member
    Join Date
    May 2018
    Location
    Russia
    Posts
    66

    Post Re: Complied app hangs on Exit Function statement

    I can't paste here more than 25000 characters, so it will be the second post...

    The program hangs at line number 462 (vbforums numeration):

    funcCHILD Code:
    1. Private Function fnDT_ASSETS_CT_ASSETS_02( _
    2.                   ByRef bFail As Boolean, _
    3.                   ByVal bShowErrors As Boolean) As Boolean
    4.         '<EhHeader>
    5.         On Error GoTo fnDT_ASSETS_CT_ASSETS_02_Err
    6.         '</EhHeader>
    7.        Const ERR_LOC = "ПРОЦЕДУРА:    fnDT_ASSETS_CT_ASSETS_02" & vbCrLf
    8.  
    9.        Dim bRetVal      As Boolean      'Возвращаемое значение (успех)
    10.        Dim bTransaction As Boolean      'Начата ли транзакция?
    11.    
    12.                                         'Записи таблицы t_TEMP_ZATR
    13.        Dim aTempZatr()  As type_TEMP_ZATR    '(редактируемые)
    14.        Dim y&, M        As Long              'Для цикла по массиву.
    15.                                         'Записи текущего документа:
    16.        Dim aRecAssDt()  As type_REGASSETS    'в t_REGASSETS (новые)
    17.        Dim aRecAssCt()  As type_REGASSETS    'в t_REGASSETS (новые)
    18.        Dim i&, N        As Long              'Для цикла по массивам.
    19.        Dim nZatrSum     As Currency     'Сумма на счёте по статье затрат.
    20.        Dim nZatrYear    As Integer      'Год начисления затрат
    21.        Dim nZatrMonth   As Integer      'Месяц начисления затрат
    22.    
    23.                                         'Записи на счетах-источниках:
    24.        Dim aRecBound()  As type_REGASSETS    'в t_REGASSETS  (редактируемые)
    25.  
    26.        Dim bFilter      As Boolean       'Временный фильтр поиска
    27.        Dim bNeedNewDate As Boolean       'Нужно обновить дату поиска?
    28.  
    29.        Dim nRestSum     As Currency      'Остаток суммы операции для списания.
    30.        Dim nRestQnt     As Currency      'Остаток кол-ва операции для списания.
    31.        Dim nOnBalnceSum As Currency      'Сумма на балансе по искомому счёту.
    32.        Dim nOnBalnceRow As Currency      'Сумма на балансе по текущей строке.
    33.     '   Dim nOnBalQNTsum As Currency      'Кол-во на балансе по искомому счёту.
    34.     '   Dim nOnBalQNTrow As Currency      'Кол-во на балансе по текущей строке.
    35.        Dim nCurrSum     As Currency      'Текущая сумма активов для переноса
    36.        Dim nCurrQnt     As Currency      'Текущее кол-во активов для переноса
    37.    
    38.        Dim nTempSum     As Currency      'Вспомогательные переменные.
    39.        Dim nFullSum     As Currency
    40.        Dim nTempQnt     As Currency
    41.      
    42.        Dim nEndOfMonth  As Integer       'Дата конца текущего месяца
    43.        
    44. 100    If nNomenId < 2& Then                      'Проверка наличия номенк-ры.
    45. 102       PrintLog ErrHeader & ERR_LOC & _
    46.              "Попытка переместить актив без номенклатуры." & vbCrLf
    47. 104       GoTo HELL
    48.        End If
    49.        
    50. 106    With t_SPR_DATES                           'Определяем дату окончания
    51. 108       .Index = "PrimaryKey"                   'месяца или, при проблемах
    52. 110       .Seek "=", nDateId                      'с разнесением, дату окон-
    53. 112       If bShowErrors Then                     'чания квартала.
    54. 114          nEndOfMonth = DateSerial(!DATE_YEAR, !DATE_MONTH \ 3 + 4, 1) - 1 - DATE_OFFSET
    55.           Else
    56. 116          nEndOfMonth = DateSerial(!DATE_YEAR, !DATE_MONTH + 1, 1) - 1 - DATE_OFFSET
    57.           End If
    58.        End With
    59.  
    60. 118    GoSub FIND_TEMP_ZATR
    61.  
    62. 120    bRetVal = True
    63. 122    GoTo HELL
    64.  
    65.           'ПОДПРОГРАММА ПОЛУЧЕНИЯ СТРУКТУРЫ АНАЛИТИКИ ТЕКУЩЕЙ СТАТЬИ ЗАТРАТ
    66. FIND_TEMP_ZATR:
    67. 124    M = 0&                                     'Кол-во записей аналитики.
    68. 126    nZatrSum = 0@                              'Сумма на счёте по ст.затрат
    69. 128    ReDim aTempZatr(1& To ARR_BLOCK)           'Массив аналитики статьи затрат
    70. 130    nZatrYear = Year(nDateId + DATE_OFFSET)
    71. 132    nZatrMonth = Month(nDateId + DATE_OFFSET)
    72. 134    With t_TEMP_ZATR
    73.    
    74.           'Проверим статью затрат. ссылки на статью затрат в 1С могут
    75.           'отсутствовать, несмотря на то, что они должны здесь
    76.           'быть (ID = 2). В этом случае индекс не учитывает ZATR_ID.
    77.      
    78. 136       If nZatrId = 2 Then
    79.          
    80.              'Кроме того, если на предыдущих итерациях не удалось
    81.              'найти затраты на счёте-источнике (bShowErrors), то
    82.              'исключаем из индекса период начисления (ищем просто
    83.              'по счёту и, при наличии, по статье затрат).
    84.          
    85. 138          If bShowErrors Then
    86. 140             .Index = "NOTCLEAN_ACC"
    87. 142             .Seek "=", True, nAccIdCt
    88.              Else
    89. 144             .Index = "NOTCLEAN_ACC_YEAR_MONTH"
    90. 146             .Seek "=", True, nAccIdCt, nZatrYear, nZatrMonth
    91.              End If
    92.           Else
    93. 148          If bShowErrors Then
    94. 150             .Index = "NOTCLEAN_ACC_ZATR"
    95. 152             .Seek "=", True, nAccIdCt, nZatrId
    96.              Else
    97. 154             .Index = "NOTCLEAN_ACC_ZATR_YEAR_MONTH"
    98. 156             .Seek "=", True, nAccIdCt, nZatrId, nZatrYear, nZatrMonth
    99.              End If
    100.           End If
    101.      
    102. 158       If .NoMatch Then
    103. 160          bFail = True
    104. 162          If bShowErrors Then PrintLog ErrHeader & ERR_LOC & _
    105.                 "Затраты на счёте-источнике (КТ) не найдены." & vbCrLf
    106. 164          GoTo HELL
    107.           End If
    108.      
    109. 166       bFilter = (nZatrId > 2) Imp (!ZATR_ID = nZatrId)
    110. 168       bFilter = bFilter And (!ACC_ID = nAccIdCt)
    111. 170       If bShowErrors = False Then
    112. 172          bFilter = bFilter And (!DATE_MONTH = nZatrMonth)
    113. 174          bFilter = bFilter And (!DATE_YEAR = nZatrYear)
    114.           End If
    115. 176       bFilter = bFilter And (!IS_NOT_CLEAN)
    116.          
    117. 178       Do While bFilter
    118. 180          M = M + 1
    119. 182          If M Mod ARR_BLOCK = 0& Then         'Приращаем массив.
    120. 184             ReDim Preserve aTempZatr(1& To M + ARR_BLOCK)
    121.              End If
    122.                                                   'Получаем текущую запись
    123. 186          If fnReadTempZatr(t_TEMP_ZATR, aTempZatr(M)) = False Then
    124. 188             PrintLog ErrHeader & ERR_LOC & _
    125.                    "Процедура fnReadTempZatr(aTempZatr) вернула ошибку." & vbCrLf
    126. 190             GoTo HELL
    127.              End If
    128.                                                   'Считаем сумму по ст.затрат.
    129. 192          nZatrSum = nZatrSum + !ASS_SUM_BALANCE
    130. 194          .MoveNext
    131. 196          If .EOF Then Exit Do
    132.          
    133. 198          bFilter = (nZatrId > 2) Imp (!ZATR_ID = nZatrId)
    134. 200          bFilter = bFilter And (!ACC_ID = nAccIdCt)
    135. 202          If bShowErrors = False Then
    136. 204             bFilter = bFilter And (!DATE_MONTH = nZatrMonth)
    137. 206             bFilter = bFilter And (!DATE_YEAR = nZatrYear)
    138.              End If
    139. 208          bFilter = bFilter And (!IS_NOT_CLEAN)
    140.           Loop
    141.        End With
    142.        
    143. 210    If M = 0& Then
    144. 212       bFail = True
    145. 214       If bShowErrors Then PrintLog ErrHeader & ERR_LOC & _
    146.              "Затраты на счёте-источнике (КТ) не найдены." & vbCrLf
    147. 216       GoTo HELL
    148.      
    149. 218    ElseIf ((nZatrSum > 0@) And (nOperSum > 0@) _
    150.           And (nZatrSum < (nOperSum - 0.004@))) _
    151.        Or ((nZatrSum < 0@) And (nOperSum < 0@) _
    152.           And (nZatrSum > (nOperSum + 0.004@))) Then
    153.      
    154. 220          bFail = True
    155. 222          If bShowErrors Then PrintLog ErrHeader & ERR_LOC & _
    156.                 "Затраты на счёте-источнике (КТ) " & _
    157.                 "в необходимой сумме не найдены." & vbCrLf
    158. 224          GoTo HELL
    159.        End If
    160.        
    161. 226    nFullSum = nOperSum
    162. 228    nRestSum = nOperSum
    163. 230    For y = 1& To M                            'Формируем суммы по структуре
    164.  
    165.           'Если поиск был осуществлён без учёта статьи затрат
    166.           '(nZatrId = 2), то в массиве aTempZatr будет несколько
    167.           'статей затрат (они упорядочены). После обработки записей,
    168.           'относящихся к первой статье затрат, вся сумма может быть
    169.           'распределена, и необходимо выйти из цикла.
    170. 232       If nRestSum = 0@ Then Exit For          'аналитики статьи затрат.
    171.  
    172. 234       With aTempZatr(y)
    173.  
    174. 236          If y > 1& Then
    175.                 'Если поиск был осуществлён без учёта статьи затрат
    176.                 '(nZatrId = 2), то для каждой новой статьи затрат
    177.                 'нужно правильно указать сумму для распределения.
    178. 238             If aTempZatr(y).ZATR_ID <> aTempZatr(y - 1).ZATR_ID Then
    179. 240                nFullSum = nRestSum
    180.                 End If
    181.              End If
    182.  
    183. 242          nTempSum = Round(nFullSum * .DELTA, 4)
    184. 244          nTempQnt = Round(.ASS_QNT_BALANCE * nTempSum / .ASS_SUM_BALANCE, 4)
    185. 246          If (.ASS_SUM_BALANCE > 0@) Then
    186.  
    187.                 'Изначально положительные остатки не должны стать < 0
    188.                 '(есть несколько итераций, и отрицательные документы
    189.                 ' могут в последствии увеличить остаток, чтобы
    190.                 ' можно было обработать пропущенный документ)
    191. 248             If (.ASS_SUM_BALANCE - nTempSum >= 0@) Then
    192. 250                .ASS_SUM_BALANCE = .ASS_SUM_BALANCE - nTempSum
    193. 252                .ASS_QNT_BALANCE = .ASS_QNT_BALANCE - nTempQnt
    194. 254                .OPER_SUM = nTempSum
    195. 256                .OPER_QNT = nTempQnt
    196. 258                nRestSum = nRestSum - .OPER_SUM
    197.  
    198.                    'Дальше обрабатываем разные погрешности округления
    199.  
    200. 260                If (.ASS_SUM_BALANCE <= 0.004@) _
    201.                    And (nRestSum >= 0.004@) Then
    202. 262                   nRestSum = nRestSum - .ASS_SUM_BALANCE
    203. 264                   .OPER_SUM = .OPER_SUM + .ASS_SUM_BALANCE
    204. 266                   .OPER_QNT = .OPER_QNT + .ASS_QNT_BALANCE
    205. 268                   .ASS_SUM_BALANCE = 0@
    206. 270                   .ASS_QNT_BALANCE = 0@
    207.                    End If
    208.  
    209. 272                If (nRestSum < 0.004@) And (nRestSum > -0.004@) _
    210.                    And (nRestSum <> 0@) _
    211.                    And (.ASS_SUM_BALANCE >= nRestSum) Then
    212. 274                   .ASS_SUM_BALANCE = .ASS_SUM_BALANCE - nRestSum
    213. 276                   .OPER_SUM = .OPER_SUM + nRestSum
    214. 278                   nRestSum = 0@
    215.                    End If
    216.  
    217.                 'Если и операция и остаток положительные, но просто
    218.                 'не хватает суммы остатка, то списываем столько,
    219.                 'сколько есть.
    220. 280             ElseIf nTempSum > 0@ Then
    221. 282                .OPER_SUM = .ASS_SUM_BALANCE
    222. 284                .OPER_QNT = .ASS_QNT_BALANCE
    223. 286                .ASS_SUM_BALANCE = 0@
    224. 288                .ASS_QNT_BALANCE = 0@
    225. 290                nRestSum = nRestSum - .OPER_SUM
    226.                 End If
    227.  
    228.              Else
    229.  
    230.                 'Те же операции для отрицательных остатков.
    231. 292             If (.ASS_SUM_BALANCE - nTempSum <= 0@) Then
    232. 294                .ASS_SUM_BALANCE = .ASS_SUM_BALANCE - nTempSum
    233. 296                .ASS_QNT_BALANCE = .ASS_QNT_BALANCE - nTempQnt
    234. 298                .OPER_SUM = nTempSum
    235. 300                .OPER_QNT = nTempQnt
    236. 302                nRestSum = nRestSum - .OPER_SUM
    237.  
    238.                    'Дальше обрабатываем разные погрешности округления
    239.  
    240. 304                If (.ASS_SUM_BALANCE >= -0.004@) _
    241.                    And (nRestSum <= -0.004@) Then
    242. 306                   nRestSum = nRestSum - .ASS_SUM_BALANCE
    243. 308                   .OPER_SUM = .OPER_SUM + .ASS_SUM_BALANCE
    244. 310                   .OPER_QNT = .OPER_QNT + .ASS_QNT_BALANCE
    245. 312                   .ASS_SUM_BALANCE = 0@
    246. 314                   .ASS_QNT_BALANCE = 0@
    247.                    End If
    248.  
    249. 316                If (nRestSum > -0.004@) And (nRestSum < 0.004@) _
    250.                    And (nRestSum <> 0@) _
    251.                    And (.ASS_SUM_BALANCE <= nRestSum) Then
    252. 318                   .ASS_SUM_BALANCE = .ASS_SUM_BALANCE - nRestSum
    253. 320                   .OPER_SUM = .OPER_SUM + nRestSum
    254. 322                   nRestSum = 0@
    255.                    End If
    256.  
    257. 324             ElseIf nTempSum < 0@ Then
    258. 326                .OPER_SUM = .ASS_SUM_BALANCE
    259. 328                .OPER_QNT = .ASS_QNT_BALANCE
    260. 330                .ASS_SUM_BALANCE = 0@
    261. 332                .ASS_QNT_BALANCE = 0@
    262. 334                nRestSum = nRestSum - .OPER_SUM
    263.                 End If
    264.              End If
    265.           End With
    266.        Next
    267.        
    268.        'Проверяем, что вся сумма операции распределилась корректно.
    269. 336    If nRestSum <> 0@ Then
    270. 338       PrintLog ErrHeader & ERR_LOC & _
    271.              "Ошибка программирования. Не смог распределить " & _
    272.              "документ по аналитике статьи затрат." & vbCrLf
    273. 340       GoTo HELL
    274.        End If
    275.    
    276.        'Имея структуру аналитики, мы теперь для каждой записи в
    277.        'aTempZatr(y) будем искать подходящие первичные документы
    278.        'и списывать с них суммы по принципу FIFO.
    279.    
    280. 342    For y = 1& To M
    281. 344       With aTempZatr(y)
    282. 346          If CBool(.OPER_SUM) Then
    283. 348             GoSub FIND_ASSETS_PRODUCTION
    284.              End If
    285.           End With
    286.        Next
    287.        
    288. 350    oWorkspase.BeginTrans                      'НАЧАЛО ТРАНЗАКЦИИ
    289. 352    bTransaction = True
    290. 354    For y = 1& To M
    291. 356       If Edit_TEMPZATR(aTempZatr(y)) = False Then
    292. 358          PrintLog ErrHeader & ERR_LOC & _
    293.                 "Процедура Edit_TEMPZATR(aTempZatr) вернула ошибку. y=" & y & vbCrLf
    294. 360          oWorkspase.Rollback
    295. 362          bTransaction = False
    296. 364          GoTo HELL
    297.           End If
    298.        Next
    299. 366    oWorkspase.CommitTrans                     'КОНЕЦ ТРАНЗАКЦИИ
    300. 368    bTransaction = False
    301.    
    302. 370    Return
    303.  
    304.            'ПОДПРОГРАММА ПОИСКА И РАСПРЕДЕЛЕНИЯ ПО СТАТЬЯМ АКТИВОВ
    305.            'СО СЧЁТА-ИСТОЧНИКА ПО СТАТЬЕ ЗАТРАТ И ПОДРАЗДЕЛЕНИЮ.
    306. FIND_ASSETS_PRODUCTION:
    307.  
    308. 372    N = 0&                                     'Кол-во связанных записей.
    309. 374    ReDim aRecBound(1& To ARR_BLOCK)           'Массив связанных активов.
    310. 376    nOnBalnceSum = 0@                          'Сумма на балансе.
    311. 378    With t_REGASSETS                           'Перебираем активы по
    312. 380       .Index = "NOTCLEAN_ACC_NOMEN_DATE_DOC"  'счёту-источнику (Кт).
    313. 382       bNeedNewDate = True
    314. 384      .SeekRecord ">=", True, nAccIdCt, aTempZatr(y).NOMEN_ID, _
    315.                            CleanDay(nAccIdCt, aTempZatr(y).NOMEN_ID), 0
    316. 386       If .NoMatch Then
    317. 388          bFail = True
    318. 390          If bShowErrors Then PrintLog ErrHeader & ERR_LOC & _
    319.                 "Активы на счёте-источнике (КТ) не найдены." & vbCrLf
    320. 392          GoTo HELL
    321.           End If
    322.  
    323. 394       Do While (!ASS_DATE <= nEndOfMonth) And (!ACC_ID = nAccIdCt) _
    324.                And (!IS_NOT_CLEAN) And (!NOMEN_ID = aTempZatr(y).NOMEN_ID)
    325.      
    326. 396          nOnBalnceRow = !ASS_SUM_BALANCE
    327.        
    328. 398          bFilter = (!ZATR_ID = aTempZatr(y).ZATR_ID)
    329. 400          bFilter = bFilter And (!PODRAZ_ID = aTempZatr(y).PODRAZ_ID)
    330.          
    331. 402          If bNeedNewDate Then                 'Обновляем дату поиска
    332. 404             CleanDay(nAccIdCt, aTempZatr(y).NOMEN_ID) = !ASS_DATE - 1
    333. 406             bNeedNewDate = False              '(однократно).
    334.              End If
    335.  
    336. 408          If bFilter Then
    337. 410             N = N + 1
    338. 412             If N Mod ARR_BLOCK = 0& Then      'Приращаем массив.
    339. 414                ReDim Preserve aRecBound(1& To N + ARR_BLOCK)
    340.                 End If
    341.                                                   'Получаем текущую запись
    342. 416             If fnReadRegassets(t_REGASSETS, aRecBound(N)) = False Then
    343. 418                PrintLog ErrHeader & ERR_LOC & _
    344.                       "Процедура fnReadRegassets(aRecBound) вернула ошибку." & vbCrLf
    345. 420                GoTo HELL
    346.                 End If
    347.                                                   'Отбираем необходимое кол-во
    348.                                                   'записей по сумме и кол-ву.
    349. 422             nOnBalnceSum = nOnBalnceSum + nOnBalnceRow
    350. 424             With aTempZatr(y)
    351. 426                If (Abs(nOnBalnceSum) >= Abs(.OPER_SUM)) _
    352.                    And ((nOnBalnceSum > 0@) = (.OPER_SUM > 0@)) Then
    353.                       Exit Do
    354.                    End If
    355.                 End With
    356.              End If
    357. 428          .MoveNext
    358. 430          If .EOF Then Exit Do
    359.           Loop
    360.        End With
    361.        
    362. 432    If N = 0& Then
    363. 434       bFail = True
    364. 436       If bShowErrors Then PrintLog ErrHeader & ERR_LOC & _
    365.              "Активы на счёте-источнике (КТ) не найдены." & vbCrLf
    366. 438       GoTo HELL
    367.        End If
    368.  
    369. 440    nRestSum = aTempZatr(y).OPER_SUM
    370. 442    nRestQnt = aTempZatr(y).OPER_QNT
    371.    
    372. 444    ReDim Preserve aRecBound(1& To N)
    373. 446    ReDim aRecAssDt(1& To N)
    374. 448    ReDim aRecAssCt(1& To N)
    375. 450    For i = 1& To N
    376. 452       With aRecBound(i)                       'Распред.сумму по строкам
    377. 454          If i = N Then
    378. 456             nCurrSum = nRestSum
    379. 458             nCurrQnt = nRestQnt
    380.              Else
    381. 460             nCurrSum = .ASS_SUM_BALANCE
    382. 462             nCurrQnt = .ASS_QNT_BALANCE
    383.              End If
    384. 464          .ASS_SUM_BALANCE = .ASS_SUM_BALANCE - nCurrSum
    385. 466          .ASS_QNT_BALANCE = .ASS_QNT_BALANCE - nCurrQnt
    386. 468          nRestSum = nRestSum - nCurrSum
    387. 470          nRestQnt = nRestQnt - nCurrQnt
    388.           End With
    389. 472       With aRecAssDt(i)                       'Проводка по дебету
    390. 474          .ASS_DATE = nDateId
    391. 476          .DOC_ID = nDocId
    392. 478          .OPER_ID = nOperId
    393. 480          .VZ_ID = aRecBound(i).VZ_ID
    394. 482          .NOMEN_ID = nNomenId
    395. 484          .PODRAZ_ID = aRecBound(i).PODRAZ_ID
    396. 486          .ZATR_ID = nZatrId
    397. 488          .ACC_ID = nAccIdDt
    398. 490          .ASS_SUM = nCurrSum
    399. 492          .ASS_NDS = 0@
    400. 494          .ASS_SUM_BALANCE = nCurrSum
    401. 496          .ASS_QNT_BALANCE = nCurrQnt
    402. 498          .ASS_QNT = nCurrQnt
    403. 500          .DESCR_ID = nDescrId
    404. 502          .REL_DOC_ID = nRelDocId
    405.           End With
    406. 504       With aRecAssCt(i)                       'Проводка по кредиту
    407. 506          .ASS_DATE = nDateId
    408. 508          .DOC_ID = nDocId
    409. 510          .OPER_ID = nOperId
    410. 512          .VZ_ID = aRecBound(i).VZ_ID
    411. 514          .NOMEN_ID = nNomenId
    412. 516          .PODRAZ_ID = aRecBound(i).PODRAZ_ID
    413. 518          .ZATR_ID = nZatrId
    414. 520          .ACC_ID = nAccIdCt
    415. 522          .ASS_SUM = -nCurrSum
    416. 524          .ASS_NDS = 0@
    417. 526          .ASS_SUM_BALANCE = 0@
    418. 528          .ASS_QNT_BALANCE = 0@
    419. 530          .ASS_QNT = -nCurrQnt
    420. 532          .DESCR_ID = nDescrId
    421. 534          .REL_DOC_ID = nRelDocId
    422.           End With
    423.        Next
    424.        
    425. 536    oWorkspase.BeginTrans                      'НАЧАЛО ТРАНЗАКЦИИ
    426. 538    bTransaction = True
    427. 540    For i = 1& To N
    428. 542       If Not ((aRecAssDt(i).ASS_SUM = 0@) And (aRecAssDt(i).ASS_QNT_BALANCE = 0@)) Then
    429. 544          If Edit_REGASSETS(aRecBound(i)) = False Then
    430. 546             PrintLog ErrHeader & ERR_LOC & _
    431.                    "Процедура Edit_REGASSETS(aRecBound) вернула ошибку. i=" & i & vbCrLf
    432. 548             oWorkspase.Rollback
    433. 550             bTransaction = False
    434. 552             GoTo HELL
    435.              End If
    436. 554          If AddNew_REGASSETS(aRecAssDt(i)) = False Then
    437. 556             PrintLog ErrHeader & ERR_LOC & _
    438.                    "Процедура AddNew_REGASSETS(aRecAssDt) вернула ошибку. i=" & i & vbCrLf
    439. 558             oWorkspase.Rollback
    440. 560             bTransaction = False
    441. 562             GoTo HELL
    442.              End If
    443. 564          If AddNew_REGASSETS(aRecAssCt(i)) = False Then
    444. 566             PrintLog ErrHeader & ERR_LOC & _
    445.                    "Процедура AddNew_REGASSETS(aRecAssCt) вернула ошибку. i=" & i & vbCrLf
    446. 568             oWorkspase.Rollback
    447. 570             bTransaction = False
    448. 572             GoTo HELL
    449.              End If
    450.           End If
    451.        Next
    452. 574    oWorkspase.CommitTrans                     'КОНЕЦ ТРАНЗАКЦИИ
    453. 576    bTransaction = False
    454.    
    455. 578    Return
    456.  
    457. HELL:
    458.        On Error Resume Next
    459. 580    If bTransaction Then oWorkspase.Rollback
    460. 582    fnDT_ASSETS_CT_ASSETS_02 = bRetVal
    461.         '<EhFooter>
    462.         Exit Function
    463.  
    464. fnDT_ASSETS_CT_ASSETS_02_Err:
    465.         PrintLog Err.Description & " BuhDoc.MProcessHeap.fnDT_ASSETS_CT_ASSETS_02. Строка:" & Erl
    466.         GoTo HELL
    467.         '</EhFooter>
    468. End Function

  11. #11

    Thread Starter
    Lively Member
    Join Date
    May 2018
    Location
    Russia
    Posts
    66

    Post Re: Complied app hangs on Exit Function statement

    Quote Originally Posted by Eduardo- View Post
    But can't you do what wqweto suggested anyway to ensure that there is no code (from your program) executing upon exiting the procedure? Discarding something without actually testing is not a good debugging practice.
    Yes, of course I've tested it. The app hangs ONLY when it's compiled and ONLY to Native Code and without any error. Therefore I've tested every line of code by placing the MsgBox functions with the line numbers in messages.

    The F8 button on "Exit Function" line does nothing but return me to the point of call (line number 100, vbforums numeration):

    subPARENT Code:
    1. Private Function fnProcessAssets_02() As Boolean
    2.         '<EhHeader>
    3.         On Error GoTo fnProcessAssets_02_Err
    4.         '</EhHeader>
    5.  
    6.        Const MAX_ITERATIONS = 10
    7.  
    8.        Dim bSuccess As Boolean          'Успех обработки операции
    9.  
    10.        Dim i           As Integer       'Номер итерации
    11.        Dim bFail       As Boolean       'Провал поиска
    12.        Dim bImp        As Boolean       'Для отдельной обработки оператора Imp
    13.                                         'Количество провалов поиска для i
    14.        Dim aFails(1 To MAX_ITERATIONS) As Long
    15.        Dim bShowErrors As Boolean       'Вывод ошибок (провалов) поиска
    16.        Dim nIntAccCt   As Integer       'Короткий номер счёта по КТ (число)
    17.        Dim bIsZatr     As Boolean       'Должна ли быть аналитика по Стат.затрат?
    18.  
    19.        'Эта процедура обрабатывает только один тип операции:
    20.        'DT_ASSETS_CT_ASSETS, то есть перемещение активов между
    21.        'активными счетами. Поиск активов на счёте-источнике может
    22.        'закончиться провалом (bFail = True), потому что зачисление
    23.        'активов на счёт ещё не произошло. Поэтому проход по таблице
    24.        't_REG_HEAP будет продолжаться циклически и остановится только если:
    25.        ' - количество провалов (aFails(i)) станет = 0;
    26.        ' - или количество провалов перестанет уменьшаться;
    27.        ' - или пока количество итераций i достигнет
    28.        '   предела = (MAX_ITERATIONS - 1);
    29.  
    30.        'После этого, если nFails>0, то будет осуществлён ещё один проход
    31.        'с параметром bShowErrors=True, чтобы отобразить ошибки поиска.
    32.  
    33. 100    PrintLog "Перераспределение активов. Очередь №2 - производство готовой продукции..."
    34.  
    35. 102    bShowErrors = False
    36. 104    For i = 1 To MAX_ITERATIONS
    37. 106       aFails(i) = 0
    38. 108       GoSub PROCESS_ASSETS
    39. 110       If (aFails(i) = 0) Then
    40.              Exit For
    41. 112       ElseIf i = MAX_ITERATIONS Then
    42. 114          bShowErrors = True
    43. 116       ElseIf i > 1 Then
    44. 118          If (aFails(i) = aFails(i - 1)) Then
    45. 120             If bShowErrors Then
    46.                    Exit For
    47.                 Else
    48. 122                bShowErrors = True
    49.                 End If
    50.              Else
    51. 124             bShowErrors = False
    52.              End If
    53.           End If
    54.        Next
    55. 126    fnProcessAssets_02 = True
    56. 128    GoTo HELL
    57.  
    58. PROCESS_ASSETS:
    59.  
    60. 130    PrintLog "Перераспределение активов. Итерация №" & i & "....."
    61.  
    62. 132    With t_REG_HEAP
    63. 134       .Index = "ISDONE_DATE"
    64. 136       .MoveFirst
    65. 138       nRecord = 1
    66. 140       nRecCount = .RecordCount
    67. 142       With frmMain.ProgressBar1
    68. 144          .Min = 1
    69. 146          .Max = nRecCount
    70. 148          .Value = nRecord
    71. 150          .Visible = True
    72.           End With
    73.  
    74. 152       oWorkspase.BeginTrans
    75. 154       Do Until .EOF Or !IS_DONE
    76. 156          nRecord = nRecord + 1
    77. 158          If nRecord Mod 50& = 0& Then
    78. 160             oWorkspase.CommitTrans
    79. 162             With frmMain
    80. 164                .ProgressBar1.Value = nRecord
    81. 166                .StatusBar1.Panels(1).Text = "Запись: " & nRecord
    82. 168                DoEvents
    83.                 End With
    84. 170             oWorkspase.BeginTrans
    85.              End If
    86.                                                   'Получаем параметры операции.
    87. 182          If fnFillVariables(t_REG_HEAP) = False Then GoTo HELL
    88.              
    89. 184          bSuccess = False
    90. 186          Select Case nOperTypId               'Запуск обработчиков операц.
    91.  
    92.              Case enum_OperTyp.otpDT_ASSETS_CT_ASSETS   'Производство продукции
    93. 188             nIntAccCt = IntAcc(sOperAccCt)
    94. 190             With t_SPR_ACCOUNTS
    95. 192                .Index = "DOUBLE_KEY"
    96. 194                .Seek "=", sOperAccCt, nOrgId
    97. 196                bIsZatr = !IS_ZATR
    98.                 End With
    99. 198             If bIsZatr Then
    100. 200                bSuccess = fnDT_ASSETS_CT_ASSETS_02(bFail, bShowErrors)
    101. 202                If bFail Then aFails(i) = aFails(i) + 1
    102. 204                GoTo SUCCESS_ANALYSE
    103.                 End If
    104.              End Select
    105.                                                   'Не анализируем успех,
    106. 206          GoTo NEXT_ROW                        'если не было обработки
    107.  
    108. SUCCESS_ANALYSE:
    109. 208          If bSuccess Then                     'Анализ успеха обработки.
    110. 210             .Edit
    111. 212             !IS_DONE = True
    112. 214             .Update
    113.              Else
    114. 216             bImp = (bFail Imp bShowErrors)
    115. 218             If bImp Then
    116. 220                PrintLog "Неудачная обработка записи t_REG_HEAP.HEAP_ID=" & nHeapId
    117.                 End If
    118.              End If
    119. 222          bFail = False
    120. NEXT_ROW:
    121. 224       .MoveNext
    122.           Loop
    123. 226       oWorkspase.CommitTrans
    124.        End With
    125. 228    Return
    126.  
    127.        '****************************************************************
    128. 230 HELL:                                             'ВЫХОД
    129.        On Error Resume Next
    130. 232    frmMain.StatusBar1.Panels(1).Text = ""
    131. 234    frmMain.ProgressBar1.Visible = False
    132. 236    PrintLog "Обработано " & nRecord - 2 & " записей."
    133. 238    nRecord = 0
    134.         '<EhFooter>
    135.         Exit Function
    136.  
    137. fnProcessAssets_02_Err:
    138.         PrintLog Err.Description & " BuhDoc.MProcessHeap.fnProcessAssets_02. Строка:" & Erl
    139.         Resume Next
    140.         '</EhFooter>
    141. End Function


    Quote Originally Posted by Eduardo- View Post
    On the other side, if the bug is not in your code, then it is obviously in a third party component (or may be VB6 itself, although unlikely).
    I have only this three references:
    Reference=*\G{00020430-0000-0000-C000-000000000046}#2.0#0#C:\windows\system32\STDOLE2.TLB#OLE Automation
    Reference=*\G{00025E01-0000-0000-C000-000000000046}#5.0#0#C:\PROGRA~1\COMMON~1\MICROS~1\DAO\dao360.dll#Microsoft DAO 3.6 Object Library
    Reference=*\G{5A2B9220-BF07-11E6-9598-0800200C9A66}#1.0#0#C:\WINDOWS\system32\OLEGuids.tlb#OLE Guid and interface definitions

    I use a couple of Krool controls here (Std-EXE version).
    https://www.vbforums.com/showthread....on-controls%29

  12. #12
    PowerPoster Arnoutdv's Avatar
    Join Date
    Oct 2013
    Posts
    4,779

    Re: Complied app hangs on Exit Function statement

    A GoSub in an actual program.
    Haven't seen that for a long time (must be back in 1992 or something)

    I would first move the GoSub to an actual Procedure (Sub).
    And then see if the program still bombs out.

  13. #13

    Thread Starter
    Lively Member
    Join Date
    May 2018
    Location
    Russia
    Posts
    66

    Re: Complied app hangs on Exit Function statement

    Quote Originally Posted by Arnoutdv View Post
    A GoSub in an actual program.
    Haven't seen that for a long time (must be back in 1992 or something)

    I would first move the GoSub to an actual Procedure (Sub).
    And then see if the program still bombs out.
    Speed is everything for this program. GoSub works faster.

    Does anybody know the difference between P-Code and Native Code that may have sense for Exit Function statement?

  14. #14
    PowerPoster wqweto's Avatar
    Join Date
    May 2011
    Posts
    3,437

    Re: Complied app hangs on Exit Function statement

    Btw, fnDT_ASSETS_CT_ASSETS_02 is called inside a transaction opened by fnProcessAssets_02.

    fnDT_ASSETS_CT_ASSETS_02 still opens nested transaction on its turn and calls Rollback on failure which will terminate all outstanding transactions, not only the innermost.

    But caller fnProcessAssets_02 does not check for failure and nevertheless will try to commit its (outer) transaction.

    Quote Originally Posted by Nouyana View Post
    Does anybody know the difference between P-Code and Native Code that may have sense for Exit Function statement?
    My bet is there is nothing wrong with these routines and the application hang is caused by completely different part your code, probably UI and probably connected with subclassing/hooking and/or buffer overflow on CopyMemory API.

    cheers,
    </wqw>

  15. #15

    Thread Starter
    Lively Member
    Join Date
    May 2018
    Location
    Russia
    Posts
    66

    Exclamation Re: Complied app hangs on Exit Function statement

    Quote Originally Posted by wqweto View Post
    Btw, fnDT_ASSETS_CT_ASSETS_02 is called inside a transaction opened by fnProcessAssets_02.

    fnDT_ASSETS_CT_ASSETS_02 still opens nested transaction on its turn and calls Rollback on failure which will terminate all outstanding transactions, not only the innermost.
    No, you are wrong:
    Quote Originally Posted by MSDN
    After you use CommitTrans, you can't undo changes made during that transaction unless the transaction is nested within another transaction that is itself rolled back. If you nest transactions, you must resolve the current transaction before you can resolve a transaction at a higher level of nesting.
    And, as I said, all code works fine in P-Code, all transactions are resolved (this is a real accounting database).

    Quote Originally Posted by wqweto View Post
    My bet is there is nothing wrong with these routines and the application hang is caused by completely different part your code, probably UI and probably connected with subclassing/hooking and/or buffer overflow on CopyMemory API.
    Maybe. So, I'm looking for cause.

    I don't use any subclassing/hooking in my code, but I use Krool controls, which does. On the other hand, I don't use controls in this part of code.

    I don't use API in this part of code (neither in subroutines). Only arrays of UDT and a lot of calculations. And DAO.

    I trapped all the execution by using MsgBox on each line. All works fine before exit.

  16. #16
    PowerPoster
    Join Date
    Feb 2017
    Posts
    3,527

    Re: Complied app hangs on Exit Function statement

    What I do in these cases is laborious and time consuming: use successive approximation:

    1 - Place the Exit Function in the middle of the procedure, compile to native code, check whether it causes the (same) error or not.
    2 - If the error still happens, move the Exit Function to 1/4 of the procedure, if the error doesn't happen, then move it to 3/4 of the procedure. Compile and test again.
    3 - Repeat (1/8, 1/16, etc) until you find the offending line.
    4 - Post the offending line here.

  17. #17
    PowerPoster
    Join Date
    Feb 2012
    Location
    West Virginia
    Posts
    13,827

    Re: Complied app hangs on Exit Function statement

    Just out of curiosity are you using timer(s) in that program? Timers do behave differently when compiled vs in the IDE so if one or more is in use it may be worthwhile to have a look at the code within the timer event(s)

  18. #18

    Thread Starter
    Lively Member
    Join Date
    May 2018
    Location
    Russia
    Posts
    66

    Arrow Re: Complied app hangs on Exit Function statement

    Quote Originally Posted by Eduardo- View Post
    What I do in these cases is laborious and time consuming: use successive approximation:

    1 - Place the Exit Function in the middle of the procedure, compile to native code, check whether it causes the (same) error or not.
    2 - If the error still happens, move the Exit Function to 1/4 of the procedure, if the error doesn't happen, then move it to 3/4 of the procedure. Compile and test again.
    3 - Repeat (1/8, 1/16, etc) until you find the offending line.
    4 - Post the offending line here.
    Thank you, Eduardo. This is the best idea for now, but the result is not realy a single line. I'll try to simplify the code again:

    Visual Basic Code:
    1. Sub subPARENT()
    2.    With RS
    3.       Do Until .EOF
    4.          nRecord = nRecord + 1        
    5.          'The program hangs on the same nRecord=3562 every time,
    6.          'but the record is absolutely usual.
    7.          bSuccess = funcCHILD()
    8.          .MoveNext
    9.       Loop
    10.    End With
    11. End Sub
    12.      
    13. Function funcCHILD() as Boolean
    14.    Dim bRetval as Boolean
    15.    
    16.    GoSub FIND_TEMP_ZATR
    17.    
    18. FIND_TEMP_ZATR:
    19.    'A lot of stuff here
    20.    For y = 1& To 11
    21.       GoSub FIND_ASSETS_PRODUCTION
    22.       'If (y = 1) Then Exit Function  'Works fine
    23.       If (y = 2) Then Exit Function  'If y >1 then app hangs
    24.    Next
    25.    Return
    26.    
    27. FIND_ASSETS_PRODUCTION:
    28.    'A lot of stuff here
    29.    oWorkspase.BeginTrans
    30.    'Some DAO operations here
    31.    oWorkspase.CommitTrans
    32.    Return
    33.    
    34.    funcCHILD = bRetval
    35.    Exit Function 'The app hangs here
    36. End Function

    I will continue the research tomorrow. There is a night in Moscow.

  19. #19

    Thread Starter
    Lively Member
    Join Date
    May 2018
    Location
    Russia
    Posts
    66

    Re: Complied app hangs on Exit Function statement

    Quote Originally Posted by DataMiser View Post
    Just out of curiosity are you using timer(s) in that program? Timers do behave differently when compiled vs in the IDE so if one or more is in use it may be worthwhile to have a look at the code within the timer event(s)
    Thank you for your answer, DataMiser. No, I don't use timers.

  20. #20
    PowerPoster Elroy's Avatar
    Join Date
    Jun 2014
    Location
    Near Nashville TN
    Posts
    6,934

    Re: Complied app hangs on Exit Function statement

    You know? This rings some faint bell in the distant past. Nouyana, you are using Service Pack 6 for your VB6 IDE, correct?

    I'm wracking my brain, but I do believe it had something to do with error trapping, maybe using Exit Function while in error trapping code? I just don't remember all the details, but I have seen this before.

    It's almost got to be something to do with the stack getting corrupted (if indeed it is the Exit Function causing the crash).
    Any software I post in these forums written by me is provided “AS IS” without warranty of any kind, expressed or implied, and permission is hereby granted, free of charge and without restriction, to any person obtaining a copy. Please understand that I’ve been programming since the mid-1970s and still have some of that code. My contemporary VB6 project is approaching 1,000 modules. In addition, I have a “VB6 random code folder” that is overflowing. I’ve been at this long enough to truly not know with absolute certainty from whence every single line of my code has come, with much of it coming from programmers under my employ who signed intellectual property transfers. I have not deliberately attempted to remove any licenses and/or attributions from any software. If someone finds that I have inadvertently done so, I sincerely apologize, and, upon notice and reasonable proof, will re-attach those licenses and/or attributions. To all, peace and happiness.

  21. #21
    PowerPoster wqweto's Avatar
    Join Date
    May 2011
    Posts
    3,437

    Re: Complied app hangs on Exit Function statement

    Quote Originally Posted by Nouyana View Post
    No, you are wrong:
    Once again, just a friendly warning: there is a problem with transaction handling on *failure* in this code. I'm not talking about the happy path where nested transactions are commited just fine.

    Let me illustrate where the problem is. Suppose you have nested transactions let's call these TRAN1 and (nested) TRAN2. The point is you cannot rollback TRAN2 without rolling back TRAN1 and this is not obvious from MSDN docs as well.

    So if you have this code

    oWorkspase.BeginTrans '--- outer transaction TRAN1

    oWorkspase.BeginTrans '--- nested transaction TRAN2
    ...
    If CheckBalance() Then
    oWorkspase.CommitTrans
    Else
    oWorkspase.Rollback
    End If

    oWorkspase.CommitTrans


    . . . the outer CommitTrans will fail if the inner Rollback is executed as it terminates *both* nested and outer transactions. After this point you cannot neither CommitTrans nor Rollback the outer transaction TRAN1.

    Note that in the happy path the outer CommitTrans will succeed just fine when the nested transaction TRAN2 has just commited successfully beforehand.

    Anyway, this probably has little to do with your current troubles though so probably comes as off-topic, sorry about that.

    cheers,
    </wqw>

  22. #22

    Thread Starter
    Lively Member
    Join Date
    May 2018
    Location
    Russia
    Posts
    66

    Arrow Re: Complied app hangs on Exit Function statement

    Quote Originally Posted by wqweto View Post
    Suppose you have nested transactions let's call these TRAN1 and (nested) TRAN2. The point is you cannot rollback TRAN2 without rolling back TRAN1
    No, man. You are wrong.
    test.zip

  23. #23
    PowerPoster Elroy's Avatar
    Join Date
    Jun 2014
    Location
    Near Nashville TN
    Posts
    6,934

    Re: Complied app hangs on Exit Function statement

    Just as an FYI, I use the DAO (DAO360.dll) extensively (for MDB databases) and have virtually no problems with it, and absolutely love it.

    I also use transactions for virtually every "write" to a database. However, I've never once nested those transactions. I'm sure there are good reasons for it ... I've just never had one.
    Any software I post in these forums written by me is provided “AS IS” without warranty of any kind, expressed or implied, and permission is hereby granted, free of charge and without restriction, to any person obtaining a copy. Please understand that I’ve been programming since the mid-1970s and still have some of that code. My contemporary VB6 project is approaching 1,000 modules. In addition, I have a “VB6 random code folder” that is overflowing. I’ve been at this long enough to truly not know with absolute certainty from whence every single line of my code has come, with much of it coming from programmers under my employ who signed intellectual property transfers. I have not deliberately attempted to remove any licenses and/or attributions from any software. If someone finds that I have inadvertently done so, I sincerely apologize, and, upon notice and reasonable proof, will re-attach those licenses and/or attributions. To all, peace and happiness.

  24. #24
    PowerPoster
    Join Date
    Feb 2017
    Posts
    3,527

    Re: Complied app hangs on Exit Function statement

    Another idea for debugging:

    Before the Exit Function, set to Nothing one by one each of the objects that are declared inside the procedure. For example RecordSets.

    And place a MsgBox after each one, like:

    Code:
        Set Obj1 = Nothing
        MsgBox "Obj1 destroyed OK"
        Set Obj2 = Nothing
        MsgBox "Obj2 destroyed OK"
        Set Obj3 = Nothing
        MsgBox "Obj3 destroyed OK"
        Set Obj4 = Nothing
        MsgBox "Obj4 destroyed OK"
        
        Exit Function
    Compile and test.

  25. #25

    Thread Starter
    Lively Member
    Join Date
    May 2018
    Location
    Russia
    Posts
    66

    Lightbulb Re: Complied app hangs on Exit Function statement

    Quote Originally Posted by Eduardo- View Post
    Another idea for debugging: Before the Exit Function, set to Nothing one by one each of the objects that are declared inside the procedure. For example RecordSets.
    I have not any object declared inside the procedure (all recordsets are declared, say, in Sub Main).
    But I found the cause of issue!
    Editing:
    The real issue is here

    1. This is not about transactions. I just removed them with no effect.
    2. The problem is in arrays of UDT. When I moved declaration to the module level, the Exit function were executed correctly. But the next call of procedure has led to the error: "This array is fixed or temporarily locked".

    So, my conclusion is that VB6 can not correctly release an:
    • UDT array
    • declared in local proc
    • and which were ReDim two or more times
    • when you compile project to Native Code (with P-Code it's all fine)
    Last edited by Nouyana; Oct 25th, 2021 at 01:28 PM. Reason: Mistake

  26. #26
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    6,687

    Re: Complied app hangs on Exit Function statement

    Those subs/functions look kind of big. Don't VB6 applications have some kind of limit on how big a function can be?
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  27. #27
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    6,687

    Re: Complied app hangs on Exit Function statement

    Quote Originally Posted by Nouyana View Post
    I have not any object declared inside the procedure (all recordsets are declared, say, in Sub Main).

    But I found the cause of issue!


    1. This is not about transactions. I just removed them with no effect.
    2. The problem is in arrays of UDT. When I moved declaration to the module level, the Exit function were executed correctly. But the next call of procedure has led to the error: "This array is fixed or temporarily locked".

    So, my conclusion is that VB6 can not correctly release an:
    • UDT array
    • declared in local proc
    • and which were ReDim two or more times
    • when you compile project to Native Code (with P-Code it's all fine)
    Effin VB6 UDTs again!
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  28. #28
    PowerPoster
    Join Date
    Feb 2017
    Posts
    3,527

    Re: Complied app hangs on Exit Function statement

    Quote Originally Posted by Nouyana View Post
    I have not any object declared inside the procedure (all recordsets are declared, say, in Sub Main).

    But I found the cause of issue!


    1. This is not about transactions. I just removed them with no effect.
    2. The problem is in arrays of UDT. When I moved declaration to the module level, the Exit function were executed correctly. But the next call of procedure has led to the error: "This array is fixed or temporarily locked".

    So, my conclusion is that VB6 can not correctly release an:
    • UDT array
    • declared in local proc
    • and which were ReDim two or more times
    • when you compile project to Native Code (with P-Code it's all fine)
    If you need further help it would be nice if you could provide a small "working" sample project to see the issue (to study the first or the second issue).
    I remember about the locked array issue but can't remember right now the details without seeing code.

  29. #29

    Thread Starter
    Lively Member
    Join Date
    May 2018
    Location
    Russia
    Posts
    66

    Re: Complied app hangs on Exit Function statement

    Quote Originally Posted by Elroy View Post
    I also use transactions for virtually every "write" to a database. However, I've never once nested those transactions. I'm sure there are good reasons for it ... I've just never had one.
    1. Outer transaction is used for speed optimization. You can make a lot of records on your hard drive at once.
    2. Nested transaction is mostly used in accounting. MSDN: "Typically, you use transactions to maintain the integrity of your data when you must both update records in two or more tables and ensure changes are completed (committed) in all tables or none at all (rolled back). For example, if you transfer money from one account to another, you might subtract an amount from one and add the amount to another. If either update fails, the accounts no longer balance."

  30. #30
    PowerPoster wqweto's Avatar
    Join Date
    May 2011
    Posts
    3,437

    Re: Complied app hangs on Exit Function statement

    Quote Originally Posted by Nouyana View Post
    No, man. You are wrong.
    test.zip
    Ooops, you have a point! Apparently JET differs than SQL Server bahavior with nested transactions and your code is fine.

    Quote Originally Posted by Nouyana View Post
    I have not any object declared inside the procedure (all recordsets are declared, say, in Sub Main).

    But I found the cause of issue!


    1. This is not about transactions. I just removed them with no effect.
    2. The problem is in arrays of UDT. When I moved declaration to the module level, the Exit function were executed correctly. But the next call of procedure has led to the error: "This array is fixed or temporarily locked".

    So, my conclusion is that VB6 can not correctly release an:
    • UDT array
    • declared in local proc
    • and which were ReDim two or more times
    • when you compile project to Native Code (with P-Code it's all fine)
    The conclusions are not correct. The problem with you code is actually using GoSub without executing proper Return.

    Here is what happens:
    1. You call GoSub
    2. Inside GoSub you use With MyArray(Index) ... End With
    3. Inside With ... End With you use GoTo HELL when some failure occurs
    4. On failure MyArray remains locked as Return statement (from GoSub) is never executed

    Here is a repro of your self-inflicted problem

    Code:
    Option Explicit
    
    Private Type MyUDT
        A As Long
        B As String
    End Type
    
    Private Sub Form_Load()
        Dim MyArray() As MyUDT
        
        ReDim MyArray(0 To 10) As MyUDT
        GoSub FIND_TEMP_ZATR
        
    HELL:
        ReDim MyArray(0 To 20) As MyUDT       '<---- errors here w/ "This array is fixed or temporarily locked"
        Debug.Print UBound(MyArray)
        Exit Sub
        
    FIND_TEMP_ZATR:
        With MyArray(5)
            GoTo HELL
        End With
        Return
    End Sub
    Either change GoTo HELL inside the GoSub to GoTo JustBeforeReturnStatement or refactor its code into a separate routine (might have issues transferring local state though).

    cheers,
    </wqw>

  31. #31

    Thread Starter
    Lively Member
    Join Date
    May 2018
    Location
    Russia
    Posts
    66

    Re: Complied app hangs on Exit Function statement

    Quote Originally Posted by Eduardo- View Post
    If you need further help it would be nice if you could provide a small "working" sample project to see the issue (to study the first or the second issue).
    I remember about the locked array issue but can't remember right now the details without seeing code.
    No, no. There is only one issue. Dots (bullets) means conditions of the issue.
    I'm trying to reproduce the issue in small example, but it is not so easy. In a small example with small UDT and just one call of proc all works fine. So I will research further.

  32. #32
    PowerPoster wqweto's Avatar
    Join Date
    May 2011
    Posts
    3,437

    Re: Complied app hangs on Exit Function statement

    Quote Originally Posted by Nouyana View Post
    No, no. There is only one issue. Dots (bullets) means conditions of the issue.
    I'm trying to reproduce the issue in small example, but it is not so easy. In a small example with small UDT and just one call of proc all works fine. So I will research further.
    Check out my repro above.

    The original code might have different issues altogether but this one (not executing Return from GoSub) I'm positive is present too.

    cheers,
    </wqw>

  33. #33

    Thread Starter
    Lively Member
    Join Date
    May 2018
    Location
    Russia
    Posts
    66

    Arrow Re: Complied app hangs on Exit Function statement

    Quote Originally Posted by wqweto View Post
    The conclusions are not correct. The problem with you code is actually using GoSub without executing proper Return.
    Here is what happens:
    1. You call GoSub
    2. Inside GoSub you use With MyArray(Index) ... End With
    3. Inside With ... End With you use GoTo HELL when some failure occurs
    4. On failure MyArray remains locked as Return statement (from GoSub) is never executed
    May be using GoSub inside With is not the best solution, but, in fact, no failure occurs and all the "End With" statements are called correctly. So, this is not the real problem. Furthermore, VB6 must release local array after Exit Function statement anyway.

  34. #34
    PowerPoster wqweto's Avatar
    Join Date
    May 2011
    Posts
    3,437

    Re: Complied app hangs on Exit Function statement

    Quote Originally Posted by Nouyana View Post
    May be using GoSub inside With is not the best solution, but, in fact, no failure occurs and all the "End With" statements are called correctly. So, this is not the real problem. Furthermore, VB6 must release local array after Exit Function statement anyway.
    Does the repro fail in your IDE?

    I can pinpoint exactly the same "GoSub + GoTo without Return" interaction in your code if you can't see it.

    cheers,
    </wqw>

  35. #35

    Thread Starter
    Lively Member
    Join Date
    May 2018
    Location
    Russia
    Posts
    66

    Re: Complied app hangs on Exit Function statement

    Quote Originally Posted by wqweto View Post
    Does the repro fail in your IDE? I can pinpoint exactly the same "GoSub + GoTo without Return" interaction in your code if you can't see it.
    The error you are talking about is "Return without GoSub", not "GoSub + GoTo without Return". Feel the difference. And no, all works fine in IDE. The issue is only with EXE (Native Code).

  36. #36
    PowerPoster wqweto's Avatar
    Join Date
    May 2011
    Posts
    3,437

    Re: Complied app hangs on Exit Function statement

    Quote Originally Posted by Nouyana View Post
    The error you are talking about is "Return without GoSub", not "GoSub + GoTo without Return". Feel the difference. And no, all works fine in IDE. The issue is only with EXE (Native Code).
    You might be right the issue is more generic and it's been discussed here in these forums.

    The problem is when a With statement execution is not matched by its End With statement execution.

    So in this code

    Code:
        With MyArray(5)
            GoTo HELL
        End With
    . . . the array remains locked as the End With takes care to unlock MyArray.

    Doesn't matter if this is inside GoSub or not actually.

    Not executing End With statement is a problem only when accessing an element of UDT arrays (e.g. the MyArray(5) part).

    For most other kind of With expressions (array of Objects or non-arrays) there is no locking going on.

    cheers,
    </wqw>

  37. #37

    Thread Starter
    Lively Member
    Join Date
    May 2018
    Location
    Russia
    Posts
    66

    Re: Complied app hangs on Exit Function statement

    Quote Originally Posted by wqweto View Post
    Not executing End With statement is a problem only when accessing an element of UDT arrays (e.g. the MyArray(5) part).
    Oh, man, please, test yourself before making a post here.

    GoToHell.zip

  38. #38
    PowerPoster wqweto's Avatar
    Join Date
    May 2011
    Posts
    3,437

    Re: Complied app hangs on Exit Function statement

    Quote Originally Posted by Nouyana View Post
    Oh, man, please, test yourself before making a post here.

    GoToHell.zip
    In subTestGoTo the local array a() As MyUDT is not deallocated as it's locked because of an early break by GoTo HELL inside With block.

    Just put a ReDim a(1 To 20) right before Exit Sub to "reveal" the array lock is outstanding.

    One can never notice this leak as there is no run-time error generated on Exit Sub (no idea why) but a ReDim fails for the same reason a deallocation would fail.

    An easy fix for this problem would be to remove all With MyArray(Index) from the code and use MyArray(Index).Data instead or remove all GoTo from inside the With MyArray(Index) blocks.

    Anyway, if the repro code above does not ring a bell I guess I cannot help more here and will stop bothering you so you can get more useful ideas by other regulars here.

    cheers,
    </wqw>

  39. #39
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    6,687

    Re: Complied app hangs on Exit Function statement

    Quote Originally Posted by Nouyana View Post
    Oh, man, please, test yourself before making a post here.

    GoToHell.zip
    wqweto is one of the most knowledgeable members here and a great contributor towards a deeper understanding of VB6 programming. You're extremely lucky he decided to devote this much time to help you, yet you've been persistently rude and scornful. I'd advise you not to be so disrespectful towards someone who is just trying to help you, especially one who has proven his caliber here on these forums.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  40. #40

    Thread Starter
    Lively Member
    Join Date
    May 2018
    Location
    Russia
    Posts
    66

    Arrow Re: Complied app hangs on Exit Function statement

    Quote Originally Posted by wqweto View Post
    In subTestGoTo the local array a() As MyUDT is not deallocated as it's locked because of an early break by GoTo HELL inside With block.
    Just put a ReDim a(1 To 20) right before Exit Sub to "reveal" the array lock is outstanding.
    Of course. But:

    Quote Originally Posted by MSDN
    In general, it's recommended that you don't jump into or out of With blocks. If statements in a With block are executed, but either the With or End With statement is not executed, a temporary variable containing a reference to the object remains in memory until you exit the procedure.
    Quote Originally Posted by Niya View Post
    you've been persistently rude and scornful. I'd advise you not to be so disrespectful towards someone who is just trying to help you.
    I'm sorry. I did not want to be rude. My words should be understood only literally. I always check/test my idea in IDE before publishing something.
    Last edited by Nouyana; Oct 21st, 2021 at 02:28 PM.

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width