![](/img/trans.png)
[英]Putting a text in the header in all Excel's sheets (loops: foreach, for) - low performance (C#)
[英]C# foreach low performance
我正在開發一個在熱敏打印機(你知道,POS 打印機等)上打印的程序這個想法是讓我的 webapps 直接在這台打印機上打印而沒有問題(例如斑馬)無論如何,問題是對於大文檔,打印需要 +/- 40 秒。 我做了一點調試,訂單直接進入作業,但是,是foreach(行)慢。
距離上次用c#開發已經很久了,所以也許有人可以幫助我提高速度
try
{
var printc = new PrintC();
var y = 0;
List<int> col = null;
int tcol = 0;
Font f;
SizeF TestSize;
Conversor convert = new Conversor();
PrintDocument p = new PrintDocument();
p.PrinterSettings.PrinterName = "RESGEST";
p.PrintPage += delegate (object sender1, PrintPageEventArgs e1)
{
Graphics g = e1.Graphics;
f = new Font("Arial", 10, FontStyle.Regular);
dynamic obj = objeto.GetValue("el");
foreach (dynamic item in obj)
{
switch ((string)item.type)
{
case "font":
// Console.WriteLine("Font: size-" + item.GetValue("size"));
f = new Font("Arial", (int)item.size, FontStyle.Regular);
break;
case "text":
TestSize = g.MeasureString((string)item.texto, f);
TestSize = g.MeasureString((string)item.texto, f, convert.w(TestSize, (string)item.w, p, tcol));
int tmpy;
e1.Graphics.DrawString(
(string)item.texto, //texto
f, //font
new SolidBrush(convert.cor((string)item.cor)), //font color
printc.container(p,
e1,
convert.x((string)item.x, TestSize, p, col, tcol), //pos x
y, //pos y
convert.w(TestSize, (string)item.w, p, tcol), //width
tmpy = convert.h(TestSize, (string)item.h, p), //height
convert.cor((string)item.background)), //background
printc.align((string)item.align) //align
);
if (col == null)
{
y += tmpy;
}
else
{
col.Add( tmpy);
}
break;
case "col":
if ((string)item.size == "0")
{
int maxValue = col.Max();
y += maxValue;
col = null;
tcol = 0;
}
else
{
col = new List<int>();
tcol = Int32.Parse((string)item.size);
}
break;
case "line":
e1.Graphics.DrawLine(new Pen(Color.Black, convert.psize((string)item.size)), 0, y += 10, (int)p.DefaultPageSettings.PrintableArea.Width, y);
y += 10;
break;
}
}
};
p.Print();
}
catch (Exception e)
{
Console.Write("Erro " + e);
}
此代碼在工作人員內部運行,該工作人員從服務器讀取數據並將其發送到此功能
您需要在 Visual Studio 中分析您的代碼,即使在免費版本中,它也具有強大的分析工具! 那么一個好的起點將是https://docs.microsoft.com/en-us/visualstudio/profiling/?view=vs-2017你可以從那里鏈接的視頻開始。
然后你需要了解,如果性能緩慢是 CPU Bound 或者某些東西(例如在那個 PrintC 對象中)綁定到外部調用等待或等待數據庫或實際打印機。
其他任何事情都是純粹的猜測,因為如果沒有外部引用,您的代碼無法在其他任何地方進行測試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.