开发者

c# how to access my thread?

i have next code:

private void button_Click(object sender, RoutedEvent开发者_StackOverflow中文版Args e)
    {
        Thread t = new Thread(Process);
        t.SetApartmentState(ApartmentState.STA);
        t.Name = "ProcessThread";
        t.Start();
    }

private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
        string msg = "Really close?";
        MessageBoxResult result =
          MessageBox.Show(
            msg,
            "Closing",
            MessageBoxButton.YesNo,
            MessageBoxImage.Warning);
        if (result == MessageBoxResult.No)
        {
            e.Cancel = true;
        }
    }

I need to do the work of code in private void Window_Closing only when It knows then the ProcessThread is still Alive/InProgress/running..

Something like IF(GetThreadByName("ProcessThread").IsAlive == true) ..

How I would write it in C#?


Declare the thread as a member variable in your class instead:

public class MyForm : Form
{
   Thread _thread;

    private void button_Click(object sender, RoutedEventArgs e)
    {
        _thread = new Thread(Process);
        _thread.SetApartmentState(ApartmentState.STA);
        _thread.Name = "ProcessThread";
        _thread.Start();
    }

    private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {

        if (_thread.IsAlive)
            //....

        string msg = "Really close?";
        MessageBoxResult result =
          MessageBox.Show(
            msg,
            "Closing",
            MessageBoxButton.YesNo,
            MessageBoxImage.Warning);
        if (result == MessageBoxResult.No)
        {
            e.Cancel = true;
        }
    }
}


One approach is to declare a member variable which specifies if the background thread is running. When the thread starts, you can set the variable to true and then set it to false when the thread's work is done.

When Window_Closing is called, you can check the variable to see if the thread has finished.

You should declare the variable as volatile, as certain compiler/runtime optimisations can stop this approach from working properly:

private volatile bool workerThreadRunning = false;


Look at System.Diagnostics.Process.GetProcessesByName().
You can also iterate through System.Diagnostics.Process.GetProcesses() to find your thread.

Or you could just put your thread i the global scope of your class so you can access it from there.

Note: I recommend you use .IsBackround=true on all the threads you create, this way a rouge thread won't stop your application from exiting properly. :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜