欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#使用Fody實(shí)現(xiàn)監(jiān)控方法執(zhí)行時(shí)間

 更新時(shí)間:2023年11月30日 09:01:13   作者:rjcql  
這篇文章主要為大家詳細(xì)介紹了C#如何使用Fody實(shí)現(xiàn)監(jiān)控方法執(zhí)行時(shí)間,文中的示例代碼講解詳細(xì),具有一定的學(xué)習(xí)價(jià)值,感興趣的小伙伴可以了解下

寫(xiě)在前面

在做性能調(diào)優(yōu)的時(shí)候,經(jīng)常需要跟蹤具體方法的執(zhí)行時(shí)間;通過(guò)插入Stopwatch的方案對(duì)代碼的侵入性太高了,所以引入了 MethodTimer.Fody 類(lèi)庫(kù),采用編譯時(shí)注入的方式給方法動(dòng)態(tài)加上Stopwatch 跟蹤代碼,只需要在目標(biāo)方法上添加 [Time] 屬性標(biāo)簽,即可實(shí)現(xiàn)注入。

需要到NuGet安裝一下Fody 和 MethodTimer.Fody

PM> Install-Package Fody
PM> Install-Package MethodTimer.Fody

代碼實(shí)現(xiàn)

// 方法執(zhí)行時(shí)長(zhǎng)記錄器
public static class MethodTimeLogger
{
    public static void Log(MethodBase methodBase, long milliseconds, string message)
    {
        Console.WriteLine($"方法:{methodBase.Name} 耗時(shí):{milliseconds}秒, 信息:{message}");
    }
}
 
// 測(cè)試目標(biāo)類(lèi)
public class MethodTracer
{
    [Time("跟蹤測(cè)試")]
    public void TestMethod()
    {
        Console.WriteLine("TestMethod: 開(kāi)始執(zhí)行");
        Thread.Sleep(123);
    }
}

調(diào)用示例:

            var methodTracer = new MethodTracer();
            methodTracer.TestMethod();

執(zhí)行結(jié)果

注意事項(xiàng)

有個(gè)需要特別注意的事情,否則注入代碼無(wú)法生效,在項(xiàng)目中添加 FodyWeavers.xml 文件并將屬性設(shè)置為"始終復(fù)制"。

Xml文件內(nèi)容如下:

<?xml version="1.0" encoding="utf-8"?>
<Weavers xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="FodyWeavers.xsd">
  <MethodTimer />
</Weavers>

直接黏貼以下內(nèi)容,vs會(huì)自動(dòng)生成xsd

<Weavers>
  <MethodTimer/>
</Weavers>

到此這篇關(guān)于C#使用Fody實(shí)現(xiàn)監(jiān)控方法執(zhí)行時(shí)間的文章就介紹到這了,更多相關(guān)C#監(jiān)控方法執(zhí)行時(shí)間內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論