2010-12-22 10 views
9

En mi aplicación, estoy realizando la lectura de mi archivo por otro hilo (otro hilo de GUI). Hay dos botones que suspenden y reanudan el subproceso, respectivamente.C# Threading.Suspend in Obsolete, thread was obsoleto?

private void BtnStopAutoUpd_Click(object sender, EventArgs e) 
     { 
      autoReadThread.Suspend(); 
     } 

private void BtnStartAutoUpd_Click(object sender, EventArgs e) 
     { 
      autoReadThread.Resume(); 
     } 

pero estoy frente a esta advertencia,

Thread.suspend ya no se utiliza. Utilice otras clases en System.Threading, como Monitor, Mutex, Evento y Semáforo, para sincronizar Subprocesos o proteger recursos. http://go.microsoft.com/fwlink/?linkid=14202

De todos modos, como solo ejecuto un hilo (en lugar de un hilo GUI), entonces ¿cómo puedo aplicar la Sincronización aquí, o monitorizarlo?

código de actualización:

class ThreadClass 
{ 

    // This delegate enables asynchronous calls for setting the text property on a richTextBox control. 
    delegate void UpdateTextCallback(object text); 

    // create thread that perform actual task 
    public Thread autoReadThread = null; 

    public ManualResetEvent _event = new ManualResetEvent(true); 

    // a new reference to rich text box 
    System.Windows.Forms.RichTextBox Textbox = null; 

    private volatile bool _run; 

    public bool Run 
    { 
     get { return _run; } 
     set { _run = value; } 
    } 

    public ThreadClass(string name, System.Windows.Forms.RichTextBox r1) 
    { 
     Textbox = r1; 
     Run = true; 
     this.autoReadThread = new Thread(new ParameterizedThreadStart(UpdateText)); 
     this.autoReadThread.Start(name); 
    } 

    private void UpdateText(object fileName) 
    { 

     //while (true) 
     //{ 
     // _event.WaitOne(); 
      while (Run) 
      { 

       if (Textbox.InvokeRequired) 
       { 
        UpdateTextCallback back = new UpdateTextCallback(UpdateText); 
        Textbox.BeginInvoke(back, new object[] { fileName }); 
        Thread.Sleep(1000); 
       } 

       else 
       { 
        string fileToUpdate = (string)fileName; 
        using (StreamReader readerStream = new StreamReader(fileToUpdate)) 
        { 
         Textbox.Text = readerStream.ReadToEnd(); 
        } 
        break; 
       //} 
      } 
     }  
    } 

} 

}

de ejecución es el valor booleano, un hilo de lo controla (Inicialmente su verdadero)

y al iniciar el subproceso que estoy creando esta instancia de clase (este comienzo hilo también) en otra clase

+0

Usted actualiza no muestra: a) Cómo se inicia su subproceso, b) el método de subproceso completo. – jgauffin

+0

InvocarRequired es siempre cierto. Su hilo no hace nada útil, todo se ejecuta en el hilo de la interfaz de usuario. –

Respuesta

8
//true makes the thread start as "running", false makes it wait on _event.Set() 
    ManualResetEvent _event = new ManualResetEvent(true); 
    Thread _thread = new Thread(ThreadFunc); 

    public void ThreadFunc(object state) 
    { 
     while (true) 
     { 
      _event.Wait(); 

      //do operations here 
     } 
    } 


    _thread.Start(); 

    // to suspend thread. 
    _event.Reset(); 

    //to resume thread 
    _event.Set(); 

Tenga en cuenta que todas las operaciones se completan primer plano el hilo está "suspendido"

lo que quieres

private void ThreadFunc(object fileName) 
{ 
    string fileToUpdate = (string)fileName; 
    while (Run) 
    { 
     _event.WaitOne(); 

     string data; 
     using (StreamReader readerStream = new StreamReader(fileToUpdate)) 
     { 
      data = readerStream.ReadToEnd(); 
     } 

     if (Textbox.InvokeRequired) 
     { 
      UpdateTextCallback back = new UpdateTextCallback(UpdateText); 
      Textbox.BeginInvoke(back, new object[] { data }); 
     } 

       Thread.Sleep(1000); 
    }  
} 


private void UpdateText(string data) 
{ 
    Textbox.Text = data; 
} 
+0

No funciona ... la ejecución se detiene en _event.Wait(); después de eso mis operaciones no se están ejecutando. – PawanS

+0

¿Ha intentado usar '_event.Set()'? Establecí el estado inicial en 'false' en el' ManualResetEvent' que lo hace esperar en el set antes de continuar – jgauffin

+0

No he llegado allí. after_evenr.Wait() Escribí mi código para ejecutar, pero wait stmnt solo se cuelga allí. _event.reset y _evenr.Set Escribí en eventos de botón. – PawanS

5

La razón suspender y reanudar están en desuso es porque no hay garantías en qué momento de la ejecución se suspenderá en el hilo. Esto es algo malo. El problema se describe here, así como una solución.

La solución debería incluir un WaitHandle (quizás AutoResetEvent o ManualResetEvent) que puede usar para indicar a su autoReadThread que se detenga/inicie.

3

Usaría el mecanismo del monitor para lograr detener y reanudar los hilos. Monitor.Wait hará que el subproceso espere el Monitor.Pulse.

private bool _pause = false; 
private object _threadLock = new object(); 

private void RunThread() 
{ 
    while (true) 
    { 
     if (_pause) 
     { 
      lock (_threadLock) 
      { 
       Monitor.Wait(_threadLock); 
      } 
     } 

     // Do work 
    } 
} 

private void PauseThread() 
{ 
    _pause = true; 
} 

private void ResumeThread() 
{ 
    _pause = false; 
    lock (_threadLock) 
    { 
     Monitor.Pulse(_threadLock); 
    } 
}