multithreading and printing

Jun 16 2007 4:05 AM
Greetings. I have an unusual problem. I have a printer intensive app, which generates a doc and sends it to laser printer. Document is generated from a documentClass which is a parameter for another printClass that encapusulates printing logic. Now print class takes the documentClass as parameter in its constructor, and then creates and starts a thread with a print function. PrintPage event takes info from parameterClass and generates doc (using printDocument here). Data is sent to a printer and all is ok. Problem is that during heavy duty printing memory contamination occurs (my guess). Doc1 gets generated and sent to printer. Doc2 gets generated and sent to printer. Doc1 prints out partially with Doc2 info (which should not occur). Doc2 prints out ok. Now private documentClass in printerClass is readonly. I tried even to lock(this) during on print function. Nothing helps. So printerClass gets created, its constructor sets everything up and starts printing in new thread, and this eventualy leads to incorrect result. Can this be a problem with GarbageCollector or does anybody have a clue? Here is sample code: using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Drawing.Printing; using System.Collections; using System.Drawing; namespace TestData { public class MyDoc { private ArrayList _strings; public ArrayList strings { get { return _strings; } } } public class PrintEngine { private Thread _t; private readonly MyDoc _myDoc; private System.Drawing.Printing.StandardPrintController _prcntrl; private PrintDocument _printDocument; private float _startx = 0; private float _starty = 0; private Font _font; public PrintEngine(MyDoc myDoc) { _myDoc = myDoc; _font = new Font("Arial", 10); _printDocument = new PrintDocument(); _prcntrl = new System.Drawing.Printing.StandardPrintController(); _printDocument.PrintPage += new PrintPageEventHandler(_printDocument_PrintPage); _t = new Thread(new ThreadStart(Print)); _t.IsBackground = true; ; _t.Start(); } private void Print() { lock (this) { _printDocument.Print(); } } void _printDocument_PrintPage(object sender, PrintPageEventArgs e) { float x = _startx; float y = _starty; foreach (string s in _myDoc) { y += 10; e.Graphics.DrawString(s, font, Brushes.Black, x, y); } } } static class Program { static void Main() { for (int i = 1; i < 6; i++) { MyDoc myDoc = new MyDoc(); /* * Add some data to myDoc */ myDoc.strings.Add(string.Format("Document {0}", i)); PrintEngine p = new PrintEngine(myDoc); /*Prints my doc in new background thread*/ } } } } The problem is that following can happen: Document 1 prints with Document 1 on it, Document 2 prints with Document 2 on it, * Document 3 prints with Document 4 on it, * Document 4 prints with Document 4 on it, Document 5 prints with Document 5 on it Cheers!!!

Answers (1)