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

 

 


Tema destacado: Guía rápida para descarga de herramientas gratuitas de seguridad y desinfección


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  ¿Hacer una pausa a un BackgrounWorker en VB.NET?
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: ¿Hacer una pausa a un BackgrounWorker en VB.NET?  (Leído 4,558 veces)
Crazy.sx


Desconectado Desconectado

Mensajes: 447



Ver Perfil
¿Hacer una pausa a un BackgrounWorker en VB.NET?
« en: 17 Diciembre 2013, 21:34 pm »

Tengo una duda, estoy usando backgroundworker y ahora se me ocurre hacer una pausa al presionar un botón. No quiero cancelar la ejecución de este backgrounworker  sino todo lo contrario, pero la verdad es que no se cómo hacerlo.

Pesaba que este control podría existir algo como:

Citar
BackgroundWorker1.state

:P   :¬¬

Espero que me puedan ayudar u orientarme mejor. Gracias.


En línea

Destruir K. LOL
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.810



Ver Perfil
Re: ¿Hacer una pausa a un BackgrounWorker en VB.NET?
« Respuesta #1 en: 18 Diciembre 2013, 07:58 am »

Pesaba que este control podría existir algo como:

Personálmente por cosas como esta nunca me gustó el BackGroundWorker.

La forma correcta de pausar/reusmir un BackgroundWorker es usando un ManualResetEvent:

EDITO: Fíjate que debes especificar manuálmente los lugares en donde el procedimiento se puede pausar (_busy.WaitOne), y esto debes especificarlo sólamente en el eventhandler DoWork.

Imports System.ComponentModel

Public Class BackgroundWork

    Private _busy As New Threading.ManualResetEvent(True)

    Private WithEvents MyWorker As New BackgroundWorker

    Public Sub StartBackgroundTask()
        MsgBox("Starting the Thread...")
        MyWorker.WorkerSupportsCancellation = True
        MyWorker.WorkerReportsProgress = True
        MyWorker.RunWorkerAsync()
    End Sub

    Private Sub MyWorker_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) _
    Handles MyWorker.DoWork

        For i = 1 To 5
            _busy.WaitOne(Threading.Timeout.Infinite)
            MyWorker.ReportProgress(MsgBox("Thread is working... " & CStr(i)))
        Next i

    End Sub

    Private Sub MyWorker_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) _
    Handles MyWorker.RunWorkerCompleted

        MsgBox("Thread Done!")

    End Sub

    Public Sub PauseWorker()

        If MyWorker.IsBusy Then
            _busy.Reset()
            MsgBox("Thread Paused!")
        End If

    End Sub

    Public Sub ContinueWorker()
        _busy.[Set]()
        MsgBox("Thread Resumed!")
    End Sub

End Class


EDITO 2: Un ejemplo mejor elaborado:

Código
  1. ' BackgroundWorker Example
  2. '
  3. ' // By Elektro H@cker
  4.  
  5. #Region " Usage Examples "
  6.  
  7. 'Public Class Form1
  8.  
  9. '    Private MyWorker As New BackgroundWork
  10.  
  11. '    Private Shadows Sub Load() Handles MyBase.Load
  12. '        MyWorker.StartBackgroundTask()
  13. '    End Sub
  14.  
  15. '    Private Sub Button_Pause_Click() Handles Button_Pause.Click
  16. '        MyWorker.Pause()
  17. '    End Sub
  18.  
  19. '    Private Sub Button_Resume_Click() Handles Button_Resume.Click
  20. '        MyWorker.Resume()
  21. '    End Sub
  22.  
  23. '    Private Sub Button_Cancel_Click() Handles Button_Cancel.Click
  24. '        MyWorker.Cancel()
  25. '    End Sub
  26.  
  27. 'End Class
  28.  
  29. #End Region
  30.  
  31. #Region " BackgroundWorker "
  32.  
  33. Public Class BackgroundWork
  34.  
  35.    ''' <summary>
  36.    ''' The BackgroundWorker object.
  37.    ''' </summary>
  38.    Private WithEvents MyWorker As New System.ComponentModel.BackgroundWorker
  39.  
  40.    ''' <summary>
  41.    ''' ManualResetEvent object to pause/resume the BackgroundWorker.
  42.    ''' </summary>
  43.    Private _busy As New Threading.ManualResetEvent(True)
  44.  
  45.  
  46.    ''' <summary>
  47.    ''' This will start the BackgroundWorker.
  48.    ''' </summary>
  49.    Public Sub StartBackgroundTask()
  50.  
  51.        MsgBox("Starting the Thread...")
  52.        MyWorker.WorkerSupportsCancellation = True
  53.        MyWorker.WorkerReportsProgress = True
  54.        MyWorker.RunWorkerAsync()
  55.  
  56.    End Sub
  57.  
  58.    ''' <summary>
  59.    ''' This is the work to do on background.
  60.    ''' </summary>
  61.    Private Sub MyWorker_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) _
  62.    Handles MyWorker.DoWork
  63.  
  64.        For i = 1 To 5
  65.  
  66.            If MyWorker.CancellationPending = True Then
  67.                e.Cancel = True
  68.                Exit For
  69.            Else
  70.                _busy.WaitOne(Threading.Timeout.Infinite) ' Indicate that here can be paused the Worker.
  71.                MyWorker.ReportProgress(
  72.                    MsgBox("Thread is working... " & i)
  73.                    )
  74.            End If
  75.  
  76.        Next i
  77.  
  78.    End Sub
  79.  
  80.    ''' <summary>
  81.    ''' This happens when the BackgroundWorker is completed.
  82.    ''' </summary>
  83.    Private Sub MyWorker_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) _
  84.    Handles MyWorker.RunWorkerCompleted
  85.  
  86.        If e.Cancelled = True Then
  87.            MsgBox("Thread cancelled")
  88.  
  89.        ElseIf e.Error IsNot Nothing Then
  90.            MsgBox("Thread error")
  91.  
  92.        Else
  93.            MsgBox("Thread Done!")
  94.  
  95.        End If
  96.  
  97.    End Sub
  98.  
  99.    ''' <summary>
  100.    ''' This will pause the BackgroundWorker.
  101.    ''' </summary>
  102.    Public Sub Pause()
  103.  
  104.        If MyWorker.IsBusy Then
  105.            _busy.Reset()
  106.            MsgBox("Thread Paused!")
  107.        End If
  108.  
  109.    End Sub
  110.  
  111.    ''' <summary>
  112.    ''' This will resume the BackgroundWorker.
  113.    ''' </summary>
  114.    Public Sub [Resume]()
  115.        _busy.[Set]()
  116.        MsgBox("Thread Resumed!")
  117.    End Sub
  118.  
  119.    ''' <summary>
  120.    ''' This will cancel the BackgroundWorker.
  121.    ''' </summary>
  122.    Public Sub Cancel()
  123.        _busy.[Set]() ' Resume worker if it is paused.
  124.        MyWorker.CancelAsync() ' Cancel it.
  125.    End Sub
  126.  
  127. End Class
  128.  
  129. #End Region

Entonces, desde el thread principal puedes hacer esto:

Código
  1. Public Class Form1
  2.  
  3.    Private MyWorker As New BackgroundWork
  4.  
  5.    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
  6.        MyWorker.StartBackgroundTask()
  7.    End Sub
  8.  
  9.    Private Sub Button_Pause_Click() Handles Button_Pause.Click
  10.        MyWorker.PauseWorker()
  11.    End Sub
  12.  
  13.    Private Sub Button_Resume_Click() Handles Button_Resume.Click
  14.        MyWorker.ContinueWorker()
  15.    End Sub
  16.  
  17. End Class

Saludos


« Última modificación: 18 Diciembre 2013, 08:26 am por EleKtro H@cker » En línea

Crazy.sx


Desconectado Desconectado

Mensajes: 447



Ver Perfil
Re: ¿Hacer una pausa a un BackgrounWorker en VB.NET?
« Respuesta #2 en: 20 Diciembre 2013, 21:09 pm »

Personálmente por cosas como esta nunca me gustó el BackGroundWorker.

La forma correcta de pausar/reusmir un BackgroundWorker es usando un ManualResetEvent:

EDITO: Fíjate que debes especificar manuálmente los lugares en donde el procedimiento se puede pausar (_busy.WaitOne), y esto debes especificarlo sólamente en el eventhandler DoWork.

Imports System.ComponentModel

Public Class BackgroundWork

    Private _busy As New Threading.ManualResetEvent(True)

    Private WithEvents MyWorker As New BackgroundWorker

    Public Sub StartBackgroundTask()
        MsgBox("Starting the Thread...")
        MyWorker.WorkerSupportsCancellation = True
        MyWorker.WorkerReportsProgress = True
        MyWorker.RunWorkerAsync()
    End Sub

    Private Sub MyWorker_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) _
    Handles MyWorker.DoWork

        For i = 1 To 5
            _busy.WaitOne(Threading.Timeout.Infinite)
            MyWorker.ReportProgress(MsgBox("Thread is working... " & CStr(i)))
        Next i

    End Sub

    Private Sub MyWorker_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) _
    Handles MyWorker.RunWorkerCompleted

        MsgBox("Thread Done!")

    End Sub

    Public Sub PauseWorker()

        If MyWorker.IsBusy Then
            _busy.Reset()
            MsgBox("Thread Paused!")
        End If

    End Sub

    Public Sub ContinueWorker()
        _busy.[Set]()
        MsgBox("Thread Resumed!")
    End Sub

End Class


EDITO 2: Un ejemplo mejor elaborado:

Código
  1. ' BackgroundWorker Example
  2. '
  3. ' // By Elektro H@cker
  4.  
  5. #Region " Usage Examples "
  6.  
  7. 'Public Class Form1
  8.  
  9. '    Private MyWorker As New BackgroundWork
  10.  
  11. '    Private Shadows Sub Load() Handles MyBase.Load
  12. '        MyWorker.StartBackgroundTask()
  13. '    End Sub
  14.  
  15. '    Private Sub Button_Pause_Click() Handles Button_Pause.Click
  16. '        MyWorker.Pause()
  17. '    End Sub
  18.  
  19. '    Private Sub Button_Resume_Click() Handles Button_Resume.Click
  20. '        MyWorker.Resume()
  21. '    End Sub
  22.  
  23. '    Private Sub Button_Cancel_Click() Handles Button_Cancel.Click
  24. '        MyWorker.Cancel()
  25. '    End Sub
  26.  
  27. 'End Class
  28.  
  29. #End Region
  30.  
  31. #Region " BackgroundWorker "
  32.  
  33. Public Class BackgroundWork
  34.  
  35.    ''' <summary>
  36.    ''' The BackgroundWorker object.
  37.    ''' </summary>
  38.    Private WithEvents MyWorker As New System.ComponentModel.BackgroundWorker
  39.  
  40.    ''' <summary>
  41.    ''' ManualResetEvent object to pause/resume the BackgroundWorker.
  42.    ''' </summary>
  43.    Private _busy As New Threading.ManualResetEvent(True)
  44.  
  45.  
  46.    ''' <summary>
  47.    ''' This will start the BackgroundWorker.
  48.    ''' </summary>
  49.    Public Sub StartBackgroundTask()
  50.  
  51.        MsgBox("Starting the Thread...")
  52.        MyWorker.WorkerSupportsCancellation = True
  53.        MyWorker.WorkerReportsProgress = True
  54.        MyWorker.RunWorkerAsync()
  55.  
  56.    End Sub
  57.  
  58.    ''' <summary>
  59.    ''' This is the work to do on background.
  60.    ''' </summary>
  61.    Private Sub MyWorker_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) _
  62.    Handles MyWorker.DoWork
  63.  
  64.        For i = 1 To 5
  65.  
  66.            If MyWorker.CancellationPending = True Then
  67.                e.Cancel = True
  68.                Exit For
  69.            Else
  70.                _busy.WaitOne(Threading.Timeout.Infinite) ' Indicate that here can be paused the Worker.
  71.                MyWorker.ReportProgress(
  72.                    MsgBox("Thread is working... " & i)
  73.                    )
  74.            End If
  75.  
  76.        Next i
  77.  
  78.    End Sub
  79.  
  80.    ''' <summary>
  81.    ''' This happens when the BackgroundWorker is completed.
  82.    ''' </summary>
  83.    Private Sub MyWorker_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) _
  84.    Handles MyWorker.RunWorkerCompleted
  85.  
  86.        If e.Cancelled = True Then
  87.            MsgBox("Thread cancelled")
  88.  
  89.        ElseIf e.Error IsNot Nothing Then
  90.            MsgBox("Thread error")
  91.  
  92.        Else
  93.            MsgBox("Thread Done!")
  94.  
  95.        End If
  96.  
  97.    End Sub
  98.  
  99.    ''' <summary>
  100.    ''' This will pause the BackgroundWorker.
  101.    ''' </summary>
  102.    Public Sub Pause()
  103.  
  104.        If MyWorker.IsBusy Then
  105.            _busy.Reset()
  106.            MsgBox("Thread Paused!")
  107.        End If
  108.  
  109.    End Sub
  110.  
  111.    ''' <summary>
  112.    ''' This will resume the BackgroundWorker.
  113.    ''' </summary>
  114.    Public Sub [Resume]()
  115.        _busy.[Set]()
  116.        MsgBox("Thread Resumed!")
  117.    End Sub
  118.  
  119.    ''' <summary>
  120.    ''' This will cancel the BackgroundWorker.
  121.    ''' </summary>
  122.    Public Sub Cancel()
  123.        _busy.[Set]() ' Resume worker if it is paused.
  124.        MyWorker.CancelAsync() ' Cancel it.
  125.    End Sub
  126.  
  127. End Class
  128.  
  129. #End Region

Entonces, desde el thread principal puedes hacer esto:

Código
  1. Public Class Form1
  2.  
  3.    Private MyWorker As New BackgroundWork
  4.  
  5.    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
  6.        MyWorker.StartBackgroundTask()
  7.    End Sub
  8.  
  9.    Private Sub Button_Pause_Click() Handles Button_Pause.Click
  10.        MyWorker.PauseWorker()
  11.    End Sub
  12.  
  13.    Private Sub Button_Resume_Click() Handles Button_Resume.Click
  14.        MyWorker.ContinueWorker()
  15.    End Sub
  16.  
  17. End Class

Saludos

Mmm... creo que seguiré usando la forma tradicional de usar hilos en background. Jeje.
Muchísimas gracias.
En línea

Destruir K. LOL
Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
hacer pausa en vb
Programación Visual Basic
cobra_90 4 8,398 Último mensaje 11 Agosto 2006, 08:43 am
por cobra_90
se me pone el pausa
Juegos y Consolas
comport 1 1,555 Último mensaje 15 Noviembre 2006, 23:22 pm
por Division-x
[batch] pausa fija « 1 2 »
Scripting
luiservv 13 12,093 Último mensaje 14 Septiembre 2010, 03:06 am
por maxx93
[DUDA] + Como hacer una pausa, pero...
Programación Visual Basic
CAR3S? 2 1,935 Último mensaje 21 Abril 2011, 15:27 pm
por CAR3S?
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines