简体   繁体   中英

C# WPF Threading : How to Stop the newly created thread in a event function(Click on a button). without affecting the main thread

Here in the below code I want to stop the thread which is created in StartInvokeExplorer function. Also the starter function in the StartInvokeExplorer is a keyhook function.

public  void InvokeExplorerStart_Click(object sender, RoutedEventArgs e)

{
            Automate.IsInvokeExplorerClicked = true;
            if (InvokeExplorer.Content.Equals("InvokeExplorerStart"))
            {
                InvokeExplorer.Content = "InvokeExplorerStop";
                StartInvokeExplorer();
                //InvokeExplorer.Dispatcher.BeginInvoke(new InvokeExplorerDelegate(StartInvokeExplorer));
            }
            else
            {
                InvokeExplorer.Content = "InvokeExplorerStart";
                StopInvokeExplorer();
            }            
        }  

public void StartInvokeExplorer()
        {
            if (XmlDataGrid.SelectedCells.Count > 0)
            {
                StartupCount = 1;
                thread = new Thread(() =>
                {
                    Starter(StartupCount);
                });
                thread.IsBackground = true;
                thread.Start();

 

            }
            else
            {
                MessageBox.Show("Please select the recorded row to fetch the new data ");
                InvokeExplorer.Content = "InvokeExplorerStart";
            }

        }


private void Starter(int cnt)
        {
            try
            {
                if (cnt > 0)
                {
                    Hook.GlobalEvents().MouseClick += (sender, e) =>
                    {
                       if (e.Button == MouseButtons.Left)
                        {
                            Automate.Show(e);
                        }                      
                    };
                    Hook.GlobalEvents().MouseDoubleClick += (sender, e) =>
                    {
                        Automate.IsDoubleClick = true;
                        Automate.Show(e);
                        Automate.IsDoubleClick = false;
                    };
                    System.Windows.Forms.Application.Run(new ApplicationContext());
                }
                else
                {
                    Hook.GlobalEvents().Dispose();
                }
            }
            catch (Exception ex)
            {
                ErrorLog.Log(ex);
            }
        }

As from what I have understand, you want to stop the running thread. This is how.

First, you need to create some stop logic. In your case, it would be some variable, like:

bool threadShouldRun;

and then inside your thread function, you should create a loop like:

void MyThreadFunc()
{
    while(threadShouldRun)
    {
        threadWork();
        Thread.Sleep(100);
    }
}

When you want to stop the thread, just set your threadShouldRun variable to false.

Sleep is needed here. Without this, thread may use 100% of processor core.

You can use an AutoResetEvent in conjunction with a CancellationToken . Something along the line of (code not tested)

CancellationTokenSource cts;
AutoResetEvent autoResetEvent;
Thread thread;

public void ThreadStart()
{
    cts = new CancellationTokenSource();
    autoResetEvent = new AutoResetEvent();

    thread = new Thread(new ParameterizedThreadStart(ThreadJob));
    thread.Start(cts.Token);
}

public void ThreadStop()
{
    cts?.Cancel();
    thread?.Join();

    cts?.Dispose();
    autoResetEvent?.Dispose();
}

public static void ThreadJob(object obj)
{
    var ct = (CancellationToken)obj;
    while (!ct.IsCancellationRequested)
    {
        if(WaitHandle.WaitAny(new[] { tc.WaitHandle, autoResetEvent}) == 1)
        {
            // Do your stuff
        }
    }
}

public void PerformJobInThread()
{
    autoResetEvent?.Set();
}

This way your thread will run until you call the ThreadStop method (actually, until you cancel your CancellationTokenSource) but you can still control when to "enable" it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM