[英]C# WPF Threading : How to Stop the newly created thread in a event function(Click on a button). without affecting the main thread
在下面的代碼中,我想停止在StartInvokeExplorer
function 中創建的線程。 StartInvokeExplorer 中的啟動器StartInvokeExplorer
也是一個 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);
}
}
據我了解,您想停止正在運行的線程。 就是這樣。
首先,您需要創建一些停止邏輯。 在您的情況下,這將是一些變量,例如:
bool threadShouldRun;
然后在你的線程 function 中,你應該創建一個循環,如:
void MyThreadFunc()
{
while(threadShouldRun)
{
threadWork();
Thread.Sleep(100);
}
}
當你想停止線程時,只需將你的threadShouldRun
變量設置為 false。
這里需要睡覺。 沒有這個,線程可能會使用 100% 的處理器內核。
您可以將AutoResetEvent
與CancellationToken
結合使用。 類似於(代碼未測試)的東西
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();
}
這樣,您的線程將一直運行,直到您調用 ThreadStop 方法(實際上,直到您取消 CancellationTokenSource),但您仍然可以控制何時“啟用”它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.