简体   繁体   中英

Multi-Threading a Task

Is there a way to multi-thread this method? The problem that I can see is that the only shared state is the cloning of the image source which takes up about half of the method time. There are about 5 to 10 thousand recipients in the list.

I've tried a ConcurrentQueue with one action added clones and another TryDequeue and processing them but over 500 items it only saves 7 seconds. Is there a way to have the imgSrc roll back or undo the changes so it doesn't have to create a new clone?

    public static void CreateImages(string fileSrc, string pathDestination, IEnumerable<Recipient> recipients)
    {
        var sfCenter = new StringFormat();
        sfCenter.Alignment = StringAlignment.Center;
        sfCenter.LineAlignment = StringAlignment.Center;

        using (var imgSrc = new System.Drawing.Bitmap(fileSrc))
        {
            foreach (var rec in recipients)
            {
                using (var imgCopy = imgSrc.Clone() as Bitmap)
                using (var graphicImage = Graphics.FromImage(imgCopy))
                {
                    graphicImage.SmoothingMode = SmoothingMode.AntiAlias;
                    graphicImage.DrawString(rec.Name, new Font("Arial", 16, FontStyle.Bold), Brushes.Black, new Rectangle(170, 105, 650, 50), sfCenter);
                    // plus other activity
                    var fileOut = pathDestination + rec.ID + ".jpg";
                    imgCopy.Save(fileOut, ImageFormat.Jpeg);
                }
            }
        }
    }

No better way found. That looks as good as it gets.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM