Ale*_*exC 7 .net c# multithreading tibco-ems heartbeat
我的应用程序中有一个错误,只有当我在调试器中暂停应用程序几分钟时,它才能显示出来.我怀疑这是由于我使用的第三方网络库有一个心跳线程,当它的心跳线程暂停时它无法ping服务器时会断开连接.
我正在尝试为此编写一个测试用例应用程序,以验证这是导致该错误的原因.为此,我需要一种方法来暂停应用程序中的所有线程(我稍后将其缩小到仅暂停我怀疑可能是心跳线程的线程)来模拟在调试器中暂停应用程序.
有谁知道如何做到这一点?一个线程甚至可能导致另一个线程入睡吗?
谢谢,亚历克斯
更新:
我最终决定我真的不需要一个应用程序为我这样做,因为重点是验证调试器中的暂停导致断开连接.所以,这就是我所做的......(最简单的方法往往是最好的......或者至少是最简单的......)
private static void Main(string[] args)
{
IPubSubAdapter adapter = BuildAdapter();
bool waitingForMessage;
adapter.Subscribe(_topic, message => waitingForMessage = false, DestinationType.Topic);
Stopwatch timePaused = new Stopwatch();
while (adapter.IsConnected)
{
Console.WriteLine("Adapter is still connected");
waitingForMessage = true;
adapter.Publish(_topic, "testmessage", DestinationType.Topic);
while (waitingForMessage)
{
Thread.Sleep(100);
}
timePaused.Reset();
timePaused.Start();
Debugger.Break();
timePaused.Stop();
Console.WriteLine("Paused for " + timePaused.ElapsedMilliseconds + "ms.");
Thread.Sleep(5000); // Give it a chance to realise it's disconnected.
}
Console.WriteLine("Adapter is disconnected!");
Console.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)
并输出:
Adapter is still connected
Paused for 10725ms.
Adapter is still connected
Paused for 13298ms.
Adapter is still connected
Paused for 32005ms.
Adapter is still connected
Paused for 59268ms.
Adapter is disconnected!
Run Code Online (Sandbox Code Playgroud)
您可以使用它来快速识别进程的线程:
using System.Diagnostics;
ProcessThreadCollection threads = Process.GetCurrentProcess().Threads;
Run Code Online (Sandbox Code Playgroud)
然后,您可以将 kernel32.dll 与 P/Invoke 结合使用,对这些线程执行您需要的任何操作。使用OpenThread获取所需线程的句柄,然后使用该句柄通过SuspendThread挂起它。
以下是这两个方法的 P/Invoke 声明:
[DllImport("kernel32.dll")]
static extern IntPtr OpenThread(uint dwDesiredAccess, bool bInheritHandle, uint dwThreadId);
[DllImport("kernel32.dll")]
static extern uint SuspendThread(IntPtr hThread);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6070 次 |
最近记录: |