elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Introducción a la Factorización De Semiprimos (RSA)


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Duda con BackgroundWorker ?
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Duda con BackgroundWorker ?  (Leído 3,732 veces)
TrashAmbishion


Desconectado Desconectado

Mensajes: 756


Ver Perfil
Duda con BackgroundWorker ?
« en: 15 Septiembre 2016, 17:30 pm »

Hola,

Que podria suceder para que una BW no se detuviera, le estoy dando la orden de cancelar y en el evento que se dispara cuando finaliza puse una variable publica que la voy comprobando con un while hasta que se haga true para poder continuar, llega bien hasta el Mywork.CancelAsync pero no se dispara el evento de que finalizo, verifique y tampoco sigue trabajando verificando ninguna de las funciones que tiene, cuando lo inicializo declaro que puede detenerse.

Es que necesito agregar a un array valores y en ese BW hay una funcion que cada cierto tiempo la usa para hacer comprobaciones.

Leyendo di con una funciona SymLock pero trate de usarla y me dio el mismo mensaje de que la coleccion ha sido modificada.

Edito: Podria ser que cuando hago el cancel no miro primero si esta ocupado (busy). ?


« Última modificación: 15 Septiembre 2016, 18:21 pm por TrashAmbishion » En línea

ivancea96


Desconectado Desconectado

Mensajes: 3.412


ASMático


Ver Perfil WWW
Re: Duda con BackgroundWorker ?
« Respuesta #1 en: 15 Septiembre 2016, 22:21 pm »

No entendí muy bien. Cuando llamas a CancelAsync, estableces el miembro CancellationPending a true. Dentro del código del worker, deberás comprobar la variable.

https://msdn.microsoft.com/es-es/library/system.componentmodel.backgroundworker.cancelasync(v=vs.110).aspx


En línea

TrashAmbishion


Desconectado Desconectado

Mensajes: 756


Ver Perfil
Re: Duda con BackgroundWorker ?
« Respuesta #2 en: 16 Septiembre 2016, 04:44 am »

Código
  1. Imports System.IO
  2. Imports System.Management
  3. Imports System.Text
  4. Imports System.Threading
  5.  
  6. Public Class BWorkerProc
  7.  
  8.    ''' <summary>
  9.    ''' The BackgroundWorker object.
  10.    ''' </summary>
  11.    Private WithEvents MyWorker As New ComponentModel.BackgroundWorker
  12.  
  13.    ''' <summary>
  14.    ''' ManualResetEvent object to pause/resume the BackgroundWorker.
  15.    ''' </summary>
  16.    Private _busy As New ManualResetEvent(True)
  17.  
  18.    Public Property StopState As Boolean
  19.  
  20.    ''' <summary>
  21.    ''' 'Flag para enviar los procesos
  22.    ''' </summary>
  23.    ''' <returns></returns>
  24.    Public Property SendProc As Boolean
  25.  
  26.    ''' <summary>
  27.    ''' This will start the BackgroundWorker.
  28.    ''' </summary>
  29.    Public Sub StartBackgroundTask()
  30.  
  31.        StopState = False
  32.  
  33.        MyWorker.WorkerSupportsCancellation = True
  34.        MyWorker.RunWorkerAsync()
  35.  
  36.    End Sub
  37.  
  38.    ''' <summary>
  39.    ''' This is the work to do on background.
  40.    ''' </summary>
  41.    Private Sub MyWorker_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles MyWorker.DoWork
  42.  
  43.        Do Until MyWorker.CancellationPending
  44.  
  45.            'Check weird process
  46.            GetProccesPath()
  47.  
  48.            'Send Process
  49.            SendProcess()
  50.  
  51.        Loop
  52.  
  53.        e.Cancel = True
  54.  
  55.    End Sub
  56.  
  57.    ''' <summary>
  58.    ''' This happens when the BackgroundWorker is completed.
  59.    ''' </summary>
  60.    Private Sub MyWorker_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) _
  61.    Handles MyWorker.RunWorkerCompleted
  62.  
  63.        If e.Cancelled = True Then
  64.            'MsgBox("Thread cancelled")
  65.            StopState = True
  66.        ElseIf e.Error IsNot Nothing Then
  67.            'MsgBox("Thread error")
  68.  
  69.        Else
  70.            'MsgBox("Thread Done!")
  71.  
  72.        End If
  73.  
  74.    End Sub
  75.  
  76.    ''' <summary>
  77.    ''' This will pause the BackgroundWorker.
  78.    ''' </summary>
  79.    Public Sub Pause()
  80.  
  81.        If MyWorker.IsBusy Then
  82.            _busy.Reset()
  83.            'MsgBox("Thread Paused!")
  84.        End If
  85.  
  86.    End Sub
  87.  
  88.    ''' <summary>
  89.    ''' This will resume the BackgroundWorker.
  90.    ''' </summary>
  91.    Public Sub [Resume]()
  92.        _busy.[Set]()
  93.        'MsgBox("Thread Resumed!")
  94.    End Sub
  95.  
  96.    ''' <summary>
  97.    ''' This will cancel the BackgroundWorker.
  98.    ''' </summary>
  99.    Public Sub Cancel()
  100.        _busy.[Set]() ' Resume worker if it is paused.
  101.        MyWorker.CancelAsync() ' Cancel it.
  102.    End Sub
  103.  
  104.  
  105. End Class
  106.  
  107.  

El cancela el worker pero no se activa el RunWorkerComplete nunca...
En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.818



Ver Perfil
Re: Duda con BackgroundWorker ?
« Respuesta #3 en: 16 Septiembre 2016, 09:27 am »

Si no proporcionas más información no creo que te podamos ayudar por que no hay ningún código que poder analizar para verificar donde está el fallo.



El cancela el worker pero no se activa el RunWorkerComplete nunca...

¿Como que no?, por supuesto que si.

Toma esa class que has publicado y testeala de esta forma tan simple:

Código
  1. Public Class Form1 : Inherits Form
  2.  
  3.    Private ReadOnly worker As New BWorkerProc
  4.  
  5.    Private Sub Button_Start_Click() Handles Button1.Click
  6.        Me.worker.StartBackgroundTask()
  7.    End Sub
  8.  
  9.    Private Sub Button_Stop_Click() Handles Button2.Click
  10.        Me.worker.Cancel()
  11.    End Sub
  12.  
  13. End Class

...teniendo así esta parte del código que has publicado:
Código
  1. ....
  2. Private Sub MyWorker_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles MyWorker.DoWork
  3.  
  4.    Do Until MyWorker.CancellationPending
  5.        Continue Do
  6.    Loop
  7.  
  8.    e.Cancel = True
  9.  
  10. End Sub
  11.  
  12. Private Sub MyWorker_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) _
  13. Handles myWorker.RunWorkerCompleted
  14.  
  15.    If e.Cancelled = True Then
  16.        MsgBox("Thread cancelled")
  17.    End If
  18.  
  19. End Sub
  20. ....



Como ves, el evento RunWorkerCompleted se dispara correctamente.





De todas formas, te recomiendo que utilices esta implementación actualizada y optimizada que escribí:

Código
  1. #Region " Option Statements "
  2.  
  3. Option Strict On
  4. Option Explicit On
  5. Option Infer Off
  6.  
  7. #End Region
  8.  
  9. #Region " Imports "
  10.  
  11. Imports System.ComponentModel
  12. Imports System.Diagnostics
  13. Imports System.Threading
  14.  
  15. #End Region
  16.  
  17. #Region " BackgroundWorker State "
  18.  
  19. ''' ----------------------------------------------------------------------------------------------------
  20. ''' <summary>
  21. ''' Specifies the state of a <see cref="BackgroundWorker"/>.
  22. ''' </summary>
  23. ''' ----------------------------------------------------------------------------------------------------
  24. Public Enum BackgroundWorkerState As Integer
  25.  
  26.    ''' <summary>
  27.    ''' The <see cref="BackgroundWorker"/> is stopped.
  28.    ''' </summary>
  29.    Stopped = 0
  30.  
  31.    ''' <summary>
  32.    ''' The <see cref="BackgroundWorker"/> is running.
  33.    ''' </summary>
  34.    Running = 1
  35.  
  36.    ''' <summary>
  37.    ''' The <see cref="BackgroundWorker"/> is paused.
  38.    ''' </summary>
  39.    Paused = 2
  40.  
  41.    ''' <summary>
  42.    ''' The <see cref="BackgroundWorker"/> is pending on a cancellation.
  43.    ''' </summary>
  44.    CancellationPending = 3
  45.  
  46.    ''' <summary>
  47.    ''' The <see cref="BackgroundWorker"/> is completed (stopped).
  48.    ''' </summary>
  49.    Completed = 4
  50.  
  51. End Enum
  52.  
  53. #End Region
  54.  
  55. #Region " My Background Work "
  56.  
  57. Public NotInheritable Class MyBackgroundWork : Implements IDisposable
  58.  
  59. #Region " Private Fields "
  60.  
  61.    ''' ----------------------------------------------------------------------------------------------------
  62.    ''' <summary>
  63.    ''' The underliying <see cref="BackgroundWorker"/> instance that runs this work on background.
  64.    ''' </summary>
  65.    ''' ----------------------------------------------------------------------------------------------------
  66.    <EditorBrowsable(EditorBrowsableState.Never)>
  67.    Friend WithEvents Worker As BackgroundWorker
  68.  
  69.    ''' ----------------------------------------------------------------------------------------------------
  70.    ''' <summary>
  71.    ''' A <see cref="ManualResetEvent"/> that serves to handle synchronous operations (Run, Pause, Resume, Cancel).
  72.    ''' </summary>
  73.    ''' ----------------------------------------------------------------------------------------------------
  74.    Private ReadOnly mreSync As ManualResetEvent
  75.  
  76.    ''' ----------------------------------------------------------------------------------------------------
  77.    ''' <summary>
  78.    ''' A <see cref="ManualResetEvent"/> that serves to handle asynchronous operations (RunAsync, CancelAsync).
  79.    ''' </summary>
  80.    ''' ----------------------------------------------------------------------------------------------------
  81.    Private ReadOnly mreAsync As ManualResetEvent
  82.  
  83.    ''' ----------------------------------------------------------------------------------------------------
  84.    ''' <summary>
  85.    ''' Indicates whether <see cref="BackGroundworker"/> has been initiated in synchronous mode.
  86.    ''' </summary>
  87.    ''' ----------------------------------------------------------------------------------------------------
  88.    Private isRunSync As Boolean = False
  89.  
  90.    ''' ----------------------------------------------------------------------------------------------------
  91.    ''' <summary>
  92.    ''' Indicates whether a synchronous cancellation operation is requested.
  93.    ''' </summary>
  94.    ''' ----------------------------------------------------------------------------------------------------
  95.    Private isCancelSyncRequested As Boolean = False
  96.  
  97.    ''' ----------------------------------------------------------------------------------------------------
  98.    ''' <summary>
  99.    ''' Indicates whether a pause operation is requested.
  100.    ''' </summary>
  101.    ''' ----------------------------------------------------------------------------------------------------
  102.    Private isPauseRequested As Boolean = False
  103.  
  104. #End Region
  105.  
  106. #Region " Properties "
  107.  
  108.    ''' ----------------------------------------------------------------------------------------------------
  109.    ''' <summary>
  110.    ''' Gets the current state of the background work.
  111.    ''' </summary>
  112.    ''' ----------------------------------------------------------------------------------------------------
  113.    ''' <value>
  114.    ''' The current state of the background work.
  115.    ''' </value>
  116.    ''' ----------------------------------------------------------------------------------------------------
  117.    Public ReadOnly Property State As BackgroundWorkerState
  118.        <DebuggerStepThrough>
  119.        Get
  120.            Return Me.stateB
  121.        End Get
  122.    End Property
  123.    ''' ----------------------------------------------------------------------------------------------------
  124.    ''' <summary>
  125.    ''' ( Backing Field )
  126.    ''' The current state of the background work.
  127.    ''' </summary>
  128.    ''' ----------------------------------------------------------------------------------------------------
  129.    Private stateB As BackgroundWorkerState = BackgroundWorkerState.Stopped
  130.  
  131. #End Region
  132.  
  133. #Region " Constructors "
  134.  
  135.    ''' ----------------------------------------------------------------------------------------------------
  136.    ''' <summary>
  137.    ''' Initializes a new instance of the <see cref="MyBackgroundWork"/> class.
  138.    ''' </summary>
  139.    ''' ----------------------------------------------------------------------------------------------------
  140.    <DebuggerNonUserCode>
  141.    Public Sub New()
  142.  
  143.        Me.Worker = New BackgroundWorker()
  144.        Me.mreSync = New ManualResetEvent(initialState:=False)
  145.        Me.mreAsync = New ManualResetEvent(initialState:=True)
  146.  
  147.    End Sub
  148.  
  149. #End Region
  150.  
  151. #Region " Public Methods "
  152.  
  153.    ''' ----------------------------------------------------------------------------------------------------
  154.    ''' <summary>
  155.    ''' Run the background work.
  156.    ''' </summary>
  157.    ''' ----------------------------------------------------------------------------------------------------
  158.    ''' <exception cref="InvalidOperationException">
  159.    ''' In order to run the BackgroundWorker instance it must be stopped or completed.
  160.    ''' </exception>
  161.    ''' ----------------------------------------------------------------------------------------------------
  162.    <DebuggerStepThrough>
  163.    Public Sub Run()
  164.  
  165.        If (Me.Worker Is Nothing) Then
  166.            Throw New ObjectDisposedException(objectName:="Worker")
  167.  
  168.        Else
  169.            Select Case Me.stateB
  170.  
  171.                Case BackgroundWorkerState.Stopped, BackgroundWorkerState.Completed
  172.                    Me.isRunSync = True
  173.                    With Me.Worker
  174.                        .WorkerSupportsCancellation = False
  175.                        .WorkerReportsProgress = False
  176.                        .RunWorkerAsync()
  177.                    End With
  178.                    Me.stateB = BackgroundWorkerState.Running
  179.                    Me.mreSync.WaitOne()
  180.  
  181.                Case Else
  182.                    Throw New InvalidOperationException("In order to run the BackgroundWorker instance it must be stopped or completed.")
  183.  
  184.            End Select
  185.  
  186.        End If
  187.  
  188.    End Sub
  189.  
  190.    ''' ----------------------------------------------------------------------------------------------------
  191.    ''' <summary>
  192.    ''' Asynchronouslly run the background work.
  193.    ''' </summary>
  194.    ''' ----------------------------------------------------------------------------------------------------
  195.    ''' <exception cref="InvalidOperationException">
  196.    ''' In order to run the BackgroundWorker instance it must be stopped or completed.
  197.    ''' </exception>
  198.    ''' ----------------------------------------------------------------------------------------------------
  199.    <DebuggerStepThrough>
  200.    Public Sub RunAsync()
  201.  
  202.        If (Me.Worker Is Nothing) Then
  203.            Throw New ObjectDisposedException(objectName:="Worker")
  204.  
  205.        Else
  206.            Select Case Me.stateB
  207.  
  208.                Case BackgroundWorkerState.Stopped, BackgroundWorkerState.Completed
  209.                    With Me.Worker
  210.                        .WorkerSupportsCancellation = True
  211.                        .WorkerReportsProgress = True
  212.                        .RunWorkerAsync()
  213.                    End With
  214.                    Me.stateB = BackgroundWorkerState.Running
  215.  
  216.                Case Else
  217.                    Throw New InvalidOperationException("In order to run the BackgroundWorker instance it must be stopped or completed.")
  218.  
  219.            End Select
  220.  
  221.        End If
  222.  
  223.    End Sub
  224.  
  225.    ''' ----------------------------------------------------------------------------------------------------
  226.    ''' <summary>
  227.    ''' Asynchronouslly pause the background work.
  228.    ''' </summary>
  229.    ''' ----------------------------------------------------------------------------------------------------
  230.    ''' <exception cref="InvalidOperationException">
  231.    ''' In order to pause the BackgroundWorker instance it must be running.
  232.    ''' </exception>
  233.    ''' ----------------------------------------------------------------------------------------------------
  234.    <DebuggerStepThrough>
  235.    Public Sub PauseAsync()
  236.  
  237.        If (Me.Worker Is Nothing) Then
  238.            Throw New ObjectDisposedException(objectName:="Worker")
  239.  
  240.        Else
  241.            Select Case Me.stateB
  242.  
  243.                Case BackgroundWorkerState.Running
  244.                    Me.isPauseRequested = True
  245.                    Me.stateB = BackgroundWorkerState.Paused
  246.                    Me.mreAsync.Reset()
  247.  
  248.                Case Else
  249.                    Throw New InvalidOperationException("In order to pause the BackgroundWorker instance it must be running.")
  250.  
  251.            End Select
  252.  
  253.        End If
  254.  
  255.    End Sub
  256.  
  257.    ''' ----------------------------------------------------------------------------------------------------
  258.    ''' <summary>
  259.    ''' Resume the background work.
  260.    ''' </summary>
  261.    ''' ----------------------------------------------------------------------------------------------------
  262.    ''' <exception cref="InvalidOperationException">
  263.    ''' In order to resume the BackgroundWorker instance it must be paused.
  264.    ''' </exception>
  265.    ''' ----------------------------------------------------------------------------------------------------
  266.    <DebuggerStepThrough>
  267.    Public Sub [Resume]()
  268.  
  269.        If (Me.Worker Is Nothing) Then
  270.            Throw New ObjectDisposedException(objectName:="Worker")
  271.  
  272.        Else
  273.            Select Case Me.stateB
  274.  
  275.                Case BackgroundWorkerState.Paused
  276.                    Me.stateB = BackgroundWorkerState.Running
  277.                    Me.isPauseRequested = False
  278.                    Me.mreAsync.Set()
  279.  
  280.                Case Else
  281.                    Throw New InvalidOperationException("In order to resume the BackgroundWorker instance must be paused.")
  282.  
  283.            End Select
  284.  
  285.        End If
  286.  
  287.    End Sub
  288.  
  289.    ''' ----------------------------------------------------------------------------------------------------
  290.    ''' <summary>
  291.    ''' Cancel the background work.
  292.    ''' <para></para>
  293.    ''' It blocks the caller thread until the remaining work is done.
  294.    ''' </summary>
  295.    ''' ----------------------------------------------------------------------------------------------------
  296.    ''' <exception cref="InvalidOperationException">
  297.    ''' In order to cancel the BackgroundWorker instance it must be running or paused.
  298.    ''' </exception>
  299.    ''' ----------------------------------------------------------------------------------------------------
  300.    <DebuggerStepThrough>
  301.    Public Sub Cancel()
  302.  
  303.        Me.isCancelSyncRequested = True
  304.        Me.CancelAsync()
  305.        Me.mreSync.WaitOne()
  306.        Me.isCancelSyncRequested = False
  307.  
  308.    End Sub
  309.  
  310.    ''' ----------------------------------------------------------------------------------------------------
  311.    ''' <summary>
  312.    ''' Asynchronouslly cancel the background work.
  313.    ''' </summary>
  314.    ''' ----------------------------------------------------------------------------------------------------
  315.    ''' <exception cref="InvalidOperationException">
  316.    ''' In order to cancel the BackgroundWorker instance it must be running or paused.
  317.    ''' </exception>
  318.    ''' ----------------------------------------------------------------------------------------------------
  319.    <DebuggerStepThrough>
  320.    Public Sub CancelAsync()
  321.  
  322.        If (Me.Worker Is Nothing) Then
  323.            Throw New ObjectDisposedException(objectName:="Worker")
  324.  
  325.        Else
  326.            Select Case Me.stateB
  327.  
  328.                Case BackgroundWorkerState.CancellationPending
  329.                    Exit Sub
  330.  
  331.                Case BackgroundWorkerState.Running, BackgroundWorkerState.Paused
  332.                    Me.mreAsync.Set() ' Resume thread if it is paused.
  333.                    Me.stateB = BackgroundWorkerState.CancellationPending
  334.                    Me.Worker.CancelAsync() ' Cancel it.
  335.  
  336.                Case Else
  337.                    Throw New InvalidOperationException("In order to cancel the BackgroundWorker instance must be running or paused.")
  338.  
  339.            End Select
  340.  
  341.        End If
  342.  
  343.    End Sub
  344.  
  345. #End Region
  346.  
  347. #Region " Private Methods "
  348.  
  349.    <DebuggerStepperBoundary>
  350.    Private Sub DoSomething()
  351.        Thread.Sleep(TimeSpan.FromSeconds(5))
  352.    End Sub
  353.  
  354. #End Region
  355.  
  356. #Region " Event-Handlers "
  357.  
  358.    ''' ----------------------------------------------------------------------------------------------------
  359.    ''' <summary>
  360.    ''' Handles the <see cref="BackgroundWorker.DoWork"/> event of the <see cref="Worker"/> instance.
  361.    ''' </summary>
  362.    ''' ----------------------------------------------------------------------------------------------------
  363.    ''' <param name="sender">
  364.    ''' The source of the event.
  365.    ''' </param>
  366.    '''
  367.    ''' <param name="e">
  368.    ''' The <see cref="DoWorkEventArgs"/> instance containing the event data.
  369.    ''' </param>
  370.    ''' ----------------------------------------------------------------------------------------------------
  371.    <DebuggerStepperBoundary>
  372.    Private Sub Worker_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) _
  373.    Handles Worker.DoWork
  374.  
  375.        Dim progress As Integer
  376.  
  377.        Dim lock As Object = ""
  378.        SyncLock lock
  379.  
  380.            For i As Integer = 0 To 100
  381.  
  382.                If (Me.Worker.CancellationPending) Then
  383.                    e.Cancel = True
  384.                    Exit For
  385.  
  386.                Else
  387.                    If (Me.isPauseRequested) Then ' Pause this thread right here.
  388.                        Me.mreAsync.WaitOne(Timeout.Infinite)
  389.                    End If
  390.  
  391.                    Me.DoSomething()
  392.  
  393.                    If Me.Worker.WorkerReportsProgress Then
  394.                        progress = i
  395.                        Me.Worker.ReportProgress(progress)
  396.                    End If
  397.  
  398.                End If
  399.  
  400.            Next i
  401.  
  402.        End SyncLock
  403.  
  404.        If (Me.Worker.WorkerReportsProgress) AndAlso Not (Me.Worker.CancellationPending) AndAlso (progress < 100) Then
  405.            Me.Worker.ReportProgress(percentProgress:=100)
  406.        End If
  407.  
  408.        If (Me.isRunSync) OrElse (Me.isCancelSyncRequested) Then
  409.            Me.mreSync.Set()
  410.        End If
  411.  
  412.    End Sub
  413.  
  414.    ''' ----------------------------------------------------------------------------------------------------
  415.    ''' <summary>
  416.    ''' Handles the <see cref="BackgroundWorker.ProgressChanged"/> event of the <see cref="Worker"/> instance.
  417.    ''' </summary>
  418.    ''' ----------------------------------------------------------------------------------------------------
  419.    ''' <param name="sender">
  420.    ''' The source of the event.
  421.    ''' </param>
  422.    '''
  423.    ''' <param name="e">
  424.    ''' The <see cref="ProgressChangedEventArgs"/> instance containing the event data.
  425.    ''' </param>
  426.    ''' ----------------------------------------------------------------------------------------------------
  427.    <DebuggerStepperBoundary>
  428.    Private Sub Worker_ProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs) _
  429.    Handles Worker.ProgressChanged
  430.  
  431.        Console.WriteLine(String.Format("Work Progress: {0:00.00}%", e.ProgressPercentage))
  432.  
  433.    End Sub
  434.  
  435.    ''' ----------------------------------------------------------------------------------------------------
  436.    ''' <summary>
  437.    ''' Handles the <see cref="BackgroundWorker.RunWorkerCompleted"/> event of the <see cref="Worker"/> instance.
  438.    ''' </summary>
  439.    ''' ----------------------------------------------------------------------------------------------------
  440.    ''' <param name="sender">
  441.    ''' The source of the event.
  442.    ''' </param>
  443.    '''
  444.    ''' <param name="e">
  445.    ''' The <see cref="RunWorkerCompletedEventArgs"/> instance containing the event data.
  446.    ''' </param>
  447.    ''' ----------------------------------------------------------------------------------------------------
  448.    <DebuggerStepperBoundary>
  449.    Private Sub Worker_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) _
  450.    Handles Worker.RunWorkerCompleted
  451.  
  452.        If (e.Cancelled) Then
  453.            Console.WriteLine("Background work cancelled.")
  454.  
  455.        ElseIf (e.Error IsNot Nothing) Then
  456.            Console.WriteLine("Background work error.")
  457.  
  458.        Else
  459.            Console.WriteLine("Background work done.")
  460.  
  461.        End If
  462.  
  463.        Me.stateB = BackgroundWorkerState.Completed
  464.  
  465.    End Sub
  466.  
  467. #End Region
  468.  
  469. #Region " IDisposable Implementation "
  470.  
  471.    ''' ----------------------------------------------------------------------------------------------------
  472.    ''' <summary>
  473.    ''' Flag to detect redundant calls when disposing.
  474.    ''' </summary>
  475.    ''' ----------------------------------------------------------------------------------------------------
  476.    Private isDisposed As Boolean
  477.    ''' ----------------------------------------------------------------------------------------------------
  478.    ''' <summary>
  479.    ''' Releases all the resources used by this instance.
  480.    ''' </summary>
  481.    ''' ----------------------------------------------------------------------------------------------------
  482.    <DebuggerStepThrough>
  483.    Public Sub Dispose() Implements IDisposable.Dispose
  484.  
  485.        Me.Dispose(isDisposing:=True)
  486.        GC.SuppressFinalize(obj:=Me)
  487.  
  488.    End Sub
  489.  
  490.    ''' ----------------------------------------------------------------------------------------------------
  491.    ''' <summary>
  492.    ''' Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  493.    ''' <para></para>
  494.    ''' Releases unmanaged and, optionally, managed resources.
  495.    ''' </summary>
  496.    ''' ----------------------------------------------------------------------------------------------------
  497.    ''' <param name="isDisposing">
  498.    ''' <see langword="True"/> to release both managed and unmanaged resources;
  499.    ''' <see langword="False"/> to release only unmanaged resources.
  500.    ''' </param>
  501.    ''' ----------------------------------------------------------------------------------------------------
  502.    <DebuggerStepThrough>
  503.    Private Sub Dispose(ByVal isDisposing As Boolean)
  504.  
  505.        If (Not Me.isDisposed) AndAlso (isDisposing) Then
  506.  
  507.            If (Me.Worker IsNot Nothing) Then
  508.                Me.Worker.Dispose()
  509.                Me.Worker = Nothing
  510.  
  511.                With Me.mreSync
  512.                    .SafeWaitHandle.Close()
  513.                    .Dispose()
  514.                End With
  515.  
  516.                With Me.mreAsync
  517.                    .SafeWaitHandle.Close()
  518.                    .Dispose()
  519.                End With
  520.  
  521.                Me.isRunSync = False
  522.                Me.stateB = BackgroundWorkerState.Stopped
  523.            End If
  524.  
  525.        End If
  526.  
  527.        Me.isDisposed = True
  528.  
  529.    End Sub
  530.  
  531. #End Region
  532.  
  533. End Class
  534.  
  535. #End Region

Ejemplo de uso:
Código
  1. Public Class Form1
  2.  
  3.    Friend Worker As MyBackgroundWork
  4.  
  5.    Private Sub Run_Click() Handles Button_Start.Click
  6.  
  7.        If (Me.Worker IsNot Nothing) Then
  8.            Select Case Me.Worker.State
  9.                Case BackgroundWorkerState.Running, BackgroundWorkerState.Paused
  10.                    Me.Worker.Cancel()
  11.                Case Else
  12.                     Do Nothing.
  13.            End Select
  14.        End If
  15.  
  16.        Me.Worker = New MyBackgroundWork
  17.        Me.Worker.RunAsync()
  18.  
  19.    End Sub
  20.  
  21.    Private Sub Pause_Click() Handles Button_Pause.Click
  22.        Me.Worker.PauseAsync()
  23.    End Sub
  24.  
  25.    Private Sub Resume_Click() Handles Button_Resume.Click
  26.        Me.Worker.Resume()
  27.    End Sub
  28.  
  29.    Private Sub Cancel_Click() Handles Button_Cancel.Click
  30.        Me.Worker.CancelAsync()
  31.    End Sub
  32.  
  33. End Class

Saludos
« Última modificación: 16 Septiembre 2016, 09:36 am por Eleкtro » En línea

TrashAmbishion


Desconectado Desconectado

Mensajes: 756


Ver Perfil
Re: Duda con BackgroundWorker ?
« Respuesta #4 en: 20 Septiembre 2016, 03:44 am »

Pues si que funcionaba el problema radicaba en que yo estaba haciendo un While hasta esperar que se disparara el evento de que ya se habia terminado el BW pero nose donde fue que leí que usar Application.DoEvents no era recomendable que era preferible usar un Thread.Slepp...

En cuanto cambie el Thread.Slepp para DoEvents funciono todo de maravillas..

El While estaba mirando una variable Booleana que se ponia a TRUE en el evento Complete del BW.

Sabrias porque sucedia eso ?

Salu2 y gracias por el código..

Ya terminé el programa y te incluí en los créditos asi como tu página despues te mando captura.
En línea

snetcancerbero

Desconectado Desconectado

Mensajes: 1


Ver Perfil
Re: Duda con BackgroundWorker ?
« Respuesta #5 en: 22 Septiembre 2016, 20:24 pm »

estimado Eleкtro, yo estoy en la misma situacion que ud. necesito encarecidamente de ser posible el programa completo, poseo cierto conocimiento de programacion y decidi crar una herramienta para controlar los jugadores de bf3 para que no sen crack en el juego y me dispuse a desemporbar mis conocimiento en c#, no me es facil pero tengo que hacerlo por el bien comun, y mi busqueda me envio aqui justo con mis propias inquietudes, porfavor necesito que me responda, gracias.
En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.818



Ver Perfil
Re: Duda con BackgroundWorker ?
« Respuesta #6 en: 23 Septiembre 2016, 20:18 pm »

El While estaba mirando una variable Booleana que se ponia a TRUE en el evento Complete del BW.

Sabrias porque sucedia eso ?

Pues no se muy bien a que te refieres, en el búcle que compartiste en el código de arriba no estás evaluando en ningún momento la variable StopState, pero bueno, ¡ya lo resolviste!.



estimado Eleкtro, yo estoy en la misma situacion que ud. necesito encarecidamente de ser posible el programa completo

Hola

Creo que te confundiste de persona y que tu mensaje en realidad va dirigido a @TrashAmbishion, puesto que el programa no es mio, jeje.

Saludos!
En línea

TrashAmbishion


Desconectado Desconectado

Mensajes: 756


Ver Perfil
Re: Duda con BackgroundWorker ?
« Respuesta #7 en: 30 Septiembre 2016, 06:20 am »

estimado Eleкtro, yo estoy en la misma situacion que ud. necesito encarecidamente de ser posible el programa completo, poseo cierto conocimiento de programacion y decidi crar una herramienta para controlar los jugadores de bf3 para que no sen crack en el juego y me dispuse a desemporbar mis conocimiento en c#, no me es facil pero tengo que hacerlo por el bien comun, y mi busqueda me envio aqui justo con mis propias inquietudes, porfavor necesito que me responda, gracias.

Pues si es conmigo la cosa el soft ya esta realizado en fase de pruebas...

Saludos y gracias nuevamente elektro
En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Pequeña duda con un comando batch (NUEVA DUDA RELACIONADA)
Scripting
revenge1252 9 9,754 Último mensaje 13 Febrero 2008, 21:41 pm
por revenge1252
Help me!! Llenar treeview desde BackgroundWorker [Solucionado por fin]
.NET (C#, VB.NET, ASP)
odeONeSs 2 5,880 Último mensaje 27 Mayo 2009, 00:51 am
por odeONeSs
Duda duda y duda de Metasploit
Bugs y Exploits
huber_nomas 4 5,786 Último mensaje 17 Febrero 2012, 14:00 pm
por MauroMasciar
Duda facil, [VIDEO QUE EXPLICA MI DUDA]
Diseño Gráfico
Ngeooz 6 8,866 Último mensaje 2 Diciembre 2013, 19:33 pm
por Ngeooz
[DUDA] Cambiar letra de unidad a archivo con un Batch [DUDA] « 1 2 »
Windows
MrMaticool 10 11,322 Último mensaje 12 Febrero 2014, 17:55 pm
por MrMaticool
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines