所以我有一种方法可以生成条码和带有该条码的标签。我们注意到,当多个用户同时生成条形码时,他们都会得到相同的文件。我使用的是ASP.NET,我正在主持应用程序和文件在内部服务器上。为什么这种方法向不同的用户吐出相同的结果
public void trickylabel(string fnsku, string title)
{
Random random = new Random();
int randomNumber = random.Next(0, 100000);
//Set barcode properties...
code.parse(fnsku); // Text
BCGDrawing drawing = new BCGDrawing(this.Server.MapPath("~") + "image"+ randomNumber.ToString() +".png", color_white);
drawing.setBarcode(code);
drawing.draw();
// Draw (or save) the image into PNG format.
Response.ContentType = "image/png";
drawing.finish(ImageFormat.Png);
Document doc = new Document(new iTextSharp.text.Rectangle(200f, 75f), 20F, 10F, 10F, 1F);
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(Request.PhysicalApplicationPath +
"\\"+randomNumber.ToString()+".pdf", FileMode.Create));
doc.Open();
iTextSharp.text.Image png = iTextSharp.text.Image.GetInstance(this.Server.MapPath("~") + "image" + randomNumber.ToString() +".png");
doc.Add(png);
//Sets pdf properties...
doc.Add(new Paragraph(title, times));
PdfAction action = new PdfAction(PdfAction.PRINTDIALOG);
writer.SetOpenAction(action);
doc.Close();
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=labels.pdf");
Response.TransmitFile(Server.MapPath("~/"+randomNumber.ToString()+".pdf"));
}
FYI ...随机()被初始化Environment.TickCount –
@保罗墙:谢谢!我想知道为什么DateTime.Now.Ticks比Random的种子更频繁地变化。在我的机器上,这个值每16毫秒只改变一次,所以你不能依靠两个连续访问者将有不同的Datetime.Now.Ticks的事实。 16毫秒是获得重复结果的很长一段时间。 – Artemix
@Artemix:关于*“...例如,您可以将Random实例存储在某个静态成员”*中。 **不要这样做!**'随机'不是线程安全的;如果您将一个实例存储为静态,那么除非您自己实施某种类型的同步,否则您将得到更奇怪的结果(即损坏)结果。 – LukeH