2012-04-17 2 views
0

을받은 보내누락 된 네트워크는 내가 여기에 대한 답을 다음과 AM /가

Calculating Bandwidth

그가 말했듯이 모든 것을 구현했습니다. 내 모니터과 같이 초기화 :

netSentCounter.CategoryName = ".NET CLR Networking"; 
netSentCounter.CounterName = "Bytes Sent"; 
netSentCounter.InstanceName = Misc.GetInstanceName(); 
netSentCounter.ReadOnly = true; 

내가 corrently 볼 수 Misc.GetInstanceName() 반환 "MyProcessName [ID]". 그러나 인스턴스가 지정된 범주에 존재하지 않는 예외를 점점 계속.

제 생각에는 실제로 보내거나받을 때까지 송수신 된 범주가 생성되지 않습니다.

<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 
    <system.net> 
     <settings> 
      <performanceCounters enabled="true" /> 
     </settings> 
    </system.net> 
</configuration> 

왜 여전히 에러가 발생합니까 :과 같이 대답에 설명 된대로

는 내가의 app.config를 추가 한?

public static class Monitoring 
{ 
    private static PerformanceCounter netSentCounter = new PerformanceCounter(); 

    //Static constructor 
    static Monitoring() 
    { 
     netSentCounter.CategoryName = ".NET CLR Networking"; 
     netSentCounter.CounterName = "Bytes Sent"; 
     netSentCounter.InstanceName = Misc.GetInstanceName(); 
     netSentCounter.ReadOnly = true; 
    } 

    /// <summary> 
    /// Returns the amount of data sent from the current application in MB 
    /// </summary> 
    /// <returns></returns> 
    public static float getNetSent() 
    { 
     return (float)netSentCounter.NextValue()/1048576; //Convert to from Bytes to MB 
    } 
} 

그리고 내 기타 클래스 :

public static class Misc 
{ 

    //Returns an instance name 
    internal static string GetInstanceName() 
    { 
     // Used Reflector to find the correct formatting: 
     string assemblyName = GetAssemblyName(); 
     if ((assemblyName == null) || (assemblyName.Length == 0)) 
     { 
      assemblyName = AppDomain.CurrentDomain.FriendlyName; 
     } 
     StringBuilder builder = new StringBuilder(assemblyName); 
     for (int i = 0; i < builder.Length; i++) 
     { 
      switch (builder[i]) 
      { 
       case '/': 
       case '\\': 
       case '#': 
        builder[i] = '_'; 
        break; 
       case '(': 
        builder[i] = '['; 
        break; 

       case ')': 
        builder[i] = ']'; 
        break; 
      } 
     } 
     return string.Format(CultureInfo.CurrentCulture, 
          "{0}[{1}]", 
          builder.ToString(), 
          Process.GetCurrentProcess().Id); 
    } 

    /// <summary> 
    /// Returns an assembly name 
    /// </summary> 
    /// <returns></returns> 
    internal static string GetAssemblyName() 
    { 
     string str = null; 
     Assembly entryAssembly = Assembly.GetEntryAssembly(); 
     if (entryAssembly != null) 
     { 
      AssemblyName name = entryAssembly.GetName(); 
      if (name != null) 
      { 
       str = name.Name; 
      } 
     } 
     return str; 
    } 
} 

편집 :

여기 내 모니터링 코드 나는 문제가 무엇인지 확인 창에서 리소스 모니터를 열었습니다. 카운터는 app.config가 그렇게하도록 설정되어 있음에도 불구하고 시작되지 않습니다. 여기

내가 (내 응용 프로그램 전송 네트워크 활동 전후에이)를 참조

enter image description here

그리고 이름이 내 방법을 반환하는 것이 아니다 것입니다. 내 메소드는 "SuperScraper [appId]"를 리턴하며 "Superscraper.vshost.exe"라고합니다.

그래서 지금은 두 가지 문제가 있습니다

- 내 카운터 앱 시작 년 - 이름에서 시작되지 않습니다 내가 당신의 예제를 시도 좋아

+0

stacktrace를 표시 할 수 있습니까? 기타는 무엇입니까? [Here] (http://pastebin.com/f371375d6)는 모든 코드이며 붙여 넣기 만 복사하면됩니다. – Reniuz

+0

기타는 내가 사용하는 라이브러리입니다. 나는 스택 추적을 게시 할 것이다. – TheGateKeeper

+1

호출 스택이 거의 비어 있습니다. 모든 것은 내 라이브러리에서 메소드를 호출하는 것입니다. 코드가 라이브러리에 있고 내 응용 프로그램에 없기 때문에 문제입니까? 내 코드는 당신과 거의 같습니다. – TheGateKeeper

답변

1

전혀 다른 것입니다. myapplicationname_pPID

: I 성능 모니터에서 해당 인스턴스 이름이 형식에서 발견 내 경우에는

netSentCounter.CategoryName = ".NET CLR Networking"; 
netSentCounter.CounterName = "Bytes Sent"; 
netSentCounter.InstanceName = Misc.GetInstanceName(); 
netSentCounter.ReadOnly = false; //<== 
netSentCounter.RawValue = 0;  //<== 

: 나는 또한 카운터 didnt 한 성능 모니터에 보여 주었다 expierenced하지만 한 내가 ReadOnly 변경 후 RawValue 속성을 설정

나는

return string.Format(CultureInfo.CurrentCulture, 
         "{0}[{1}]", 
         builder.ToString(), 
         Process.GetCurrentProcess().Id); 

에 GetInstanceName 방법 라인 변경 그래서 후

카운터가 작동하기 시작한 것 같습니다. 여기

당신이 그것을 사용하는 마친 후 (netSentCounter.RemoveInstance()) 카운터를 제거하는 방법에 대한 방법을 add and remove counter instance

이 또한 생각하는 참조입니다.

+0

나는 그것이 무엇이 잘못되었는지 정말로 모른다. 나는 당신의 코드를 사용하여 그것을 만들 수 있었지만 결코 아무것도 반환하지 않는다. 그것이하는 것은 0을 다시 돌려주는 것입니다.직접 만들지 않으면 값을 반환합니다. 당신이'netSentCounter.RawValue = 0;'때문이라고 생각하십니까? 당신이 값을 반환 했습니까? – TheGateKeeper

+0

글쎄, 나는 그것을 테스트하지 못했고, 나는 왜 당신이 에러를 내는지 알아 내려고 노력했다. – Reniuz

+0

이름이 일치하고 같은 위치에 만들고 있지만 값은 변경되지 않습니다. 만약 내가 그것을 만들지 않고 자신의 것으로 만들도록 시키면 (예를 들어 요청을 보내서) 값을보고합니다. 당신이 똑같은 행동을한다면 테스트 할 수 있니? – TheGateKeeper

3

좋아, 나는 마침내 그것을 알아 냈다. Calculating Bandwidth에 나열된 단계는 구형 인 것으로 보이며 더 이상 유효하지 않습니다 .Net 4.

나는 전체 과정을 설명하여 잘 할 수 있습니다.

첫째로, 당신은 당신의 app.config에이를 추가해야 닷넷 4.0 전에,이 응용 프로그램은 시작에 카운터 (그리고 예를 들어를 만들 때 네트워크 카운터를 작성했다

<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 
    <system.net> 
     <settings> 
      <performanceCounters enabled="true" /> 
     </settings> 
    </system.net> 
</configuration> 

귀하의 신청서가 요청을 보냄). .Net 4.0에서는 카운터를 사용할 때이를 생성합니다. 예. 이것을 설정하지 않으면 카운터가 생성되지 않습니다.

이제는 내가 대부분의 시간을 낭비했습니다. 자연스럽게 생성 된 경우와 동일한 이름의 성능 카운터를 만들면 값을 얻을 것이라는 잘못된 가정하에있었습니다. 그러나이 모든 것은 진짜 카운터가 나타나지 못하도록 차단합니다.

그래서이 일을 :

//In .Net 4.0 the category is called .NET CLR Networking 4.0.0.0 and not .NET CLR Networking 
netSentCounter.CategoryName = ".NET CLR Networking 4.0.0.0"; 
netSentCounter.CounterName = "Bytes Sent"; 
netSentCounter.InstanceName = Misc.GetInstanceName(); 
netSentCounter.ReadOnly = false; //<== 
netSentCounter.RawValue = 0;  //<== 

간단히 블록 실제 카운터.

자연스럽게 시작해야합니다. 이 작업을 수행하는 가장 좋은 방법은 단순히 응용 프로그램 시작시 눈속임 요청을 보내는 것입니다, 다음 사용하여 성능 카운터에 "수신"

//Send spoof request here 
netSentCounter.CategoryName = ".NET CLR Networking 4.0.0.0"; 
netSentCounter.CounterName = "Bytes Sent"; 
netSentCounter.InstanceName = Misc.GetInstanceName(); 
netSentCounter.ReadOnly = true; 

마지막 요점. 인스턴스 이름은 더 이상 ApplicationName[appId]이 아닙니다. 지금은 다음과 같습니다

[ApplicationName] .exe_p [appId] _r [the CLR id hosting your application]이 누군가의 시간을 절약 할 수 [ApplicationDomain]

희망을 _ad!

+0

Upvote "in .Net 4.0에서는 카운터를 사용할 때 카운터 생성을 지시합니다." 감사합니다 :) – Henners

+0

그건 그렇고, 여기에 .NET 성능 카운터에 대한 전체 인스턴스 이름을 얻는 올바른 방법입니다 : http://stackoverflow.com/questions/10196432/getting-the-clr-id – Funbit

관련 문제