Detection task manager of NancyFx framework, nancyfx framework
First, create an empty project with the same steps as the previous NancyFx series.
Create three folders: Models, Module, and Views.
Install the components separately.
- JQuery
- Microsoft. AspNet. SignalR
- Microsoft. Owin
- Nancy
- Nancy. Owin
Then add the CPUHub class and Broadcaster class to the Model class.
CPUHub class
1 public class CPUHub:Hub 2 { 3 private readonly Broadcaster broadcaster; 4 public CPUHub():this(Broadcaster.broadcaster) 5 { 6 7 } 8 public CPUHub(Broadcaster broadcaster) 9 {10 this.broadcaster = broadcaster;11 }12 }
View Code
Broadcaster class
1 public class Broadcaster 2 { 3 private readonly static Lazy<Broadcaster> lazy = new Lazy<Broadcaster>(()=>new Broadcaster(GlobalHost.ConnectionManager.GetHubContext<CPUHub>().Clients)); 4 5 private readonly TimeSpan timeSpan = TimeSpan.FromMilliseconds(1000); 6 private readonly Timer timer; 7 public static Broadcaster broadcaster 8 { 9 get { return lazy.Value; }10 }11 private IHubConnectionContext hubConnectionContext12 {13 get;14 set;15 }16 private Broadcaster(IHubConnectionContext hubConnectionContexts)17 {18 hubConnectionContext = hubConnectionContexts;19 timer = new Timer(BroadcastCpuUsage,null,timeSpan,timeSpan);20 }21 private void BroadcastCpuUsage(object o)22 {23 string cpu = GetCurrentCpu();24 25 }26 private string GetCurrentCpu()27 {28 string currentCpu = "";29 HttpClient httpClient = new HttpClient();30 httpClient.BaseAddress = new Uri("http://localhost:3039");31 var response = httpClient.GetAsync("api/cpu").Result;32 if (response.IsSuccessStatusCode)33 {34 currentCpu = response.Content.ReadAsStringAsync().Result;35 }36 return currentCpu;37 }38 }
Then add the CPUModule class to the Module.
1 public class CPUModule:NancyModule 2 { 3 PerformanceCounter performanceCounter; 4 public CPUModule():base("api/cpu") 5 { 6 InitializePerformanceCounter(); 7 Get("/",Lexan=> 8 { 9 int cpu = (int)Math.Ceiling(performanceCounter.NextValue());10 return Response.AsText(cpu.ToString());11 });12 }13 private void InitializePerformanceCounter()14 {15 performanceCounter = new PerformanceCounter();16 performanceCounter.CategoryName = "";17 performanceCounter.CounterName = "";18 performanceCounter.InstanceName = "";19 performanceCounter.NextValue();20 Thread.Sleep(1000);21 }22 }
Then the index.html page is under the root directory.
1 <!DOCTYPE html> 2
Add the Startup class to the root directory.
1 [assembly:OwinStartup(typeof( NancyFxTaskManager.Startup))] 2 namespace NancyFxTaskManager 3 { 4 public class Startup 5 { 6 public void Configuration(IAppBuilder app) 7 { 8 app.MapSignalR().UseNancy(); 9 10 }11 }12 }
Now, we are ready to see the running effect.
Thank you for watching dalao. If any, please kindly advise.