473,769 Members | 4,831 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

InvalidOperatio nException: object is currently in use elsewhere


When i try to re-use brushes or pens over multiple threads, i often get
an InvalidOperatio nException with the message 'object is currently in use
elsewhere'.
I also tried this by re-using fonts but no problems there.

So, it looks like brushes and pens cannot be used in different threads
simultaneously.
Looks like a dotnet bug to me.

This exception is easily reproducible with the following code, both on single
and multi processor systems:

Jos Lavrijsen (Philips Medical Systems)
using System;
using System.Drawing;
using System.Drawing. Imaging;

namespace Jos.Test.Proble ms {

/// <summary>
/// This test shows that brushes cannot be shared over multiple threads
/// Author: Jos Lavrijsen
/// Creation: 26 November 2005
/// </summary>
public class MTDrawProblem {

delegate void Delegate();
static Brush brush = new SolidBrush(Colo r.Blue);

public static void Start() {
for (int i = 0; i < 100; i++) {
new Delegate(TestIt ).BeginInvoke(n ull, null);
}
}

private static void TestIt() {
try {
Bitmap bitmap = new Bitmap(1024, 1024,
PixelFormat.For mat32bppPArgb);
Graphics g = Graphics.FromIm age(bitmap);
g.FillRectangle (brush, 0, 0, 1024, 1024);
} catch(InvalidOp erationExceptio n ex) {
Console.Out.Wri teLine(ex);
}
}
}
}

Dec 19 '05 #1
4 10364

Jos Lavrijsen wrote:
When i try to re-use brushes or pens over multiple threads, i often get
an InvalidOperatio nException with the message 'object is currently in use
elsewhere'.
I also tried this by re-using fonts but no problems there.

So, it looks like brushes and pens cannot be used in different threads
simultaneously. From the docs (my emphasis):
Brush Class

Thread Safety
Any public static members of this type are thread safe. **Any instance
members are not guaranteed to be thread safe.**
Looks like a dotnet bug to me.


Looks like behaviour as documented to me. Fonts aren't guaranteed
thread-safe either, so you've been lucky so far.

--
Larry Lard
Replies to group please

Dec 19 '05 #2
Jos Lavrijsen <Jo**********@d iscussions.micr osoft.com> wrote:
When i try to re-use brushes or pens over multiple threads, i often get
an InvalidOperatio nException with the message 'object is currently in use
elsewhere'.
I also tried this by re-using fonts but no problems there.

So, it looks like brushes and pens cannot be used in different threads
simultaneously.
Looks like a dotnet bug to me.


How can it be a bug when it's the documented behaviour, as Larry
pointed out earlier?

Do you really need to be doing UI operations on multiple threads in the
first place? Usually all UI operations should occur on a single thread.
Given the "Philips Medical Systems" bit, I guess you may be writing a
medical imaging application, in which case it's more likely that it's a
reasonable design, but it's worth checking.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Dec 20 '05 #3

Ok, brushes may not be thread safe but it feels strange that an exception
is thrown even though i am not modifying the brush.
Apparently, a brush is not only a description but maybe also contains logic
to perform the actual drawing.

Drawing on bitmaps has nothing to do with UI operations.
In my use-case i am processing a huge amount of images in background to
be exported. To get a high throughput on multiprocessor systems, i use
multiple threads to do this processing.
I try to reuse brushes, fonts and pens to minimize the amount of garbage
produced.

Jos Lavrijsen.

"Jon Skeet [C# MVP]" wrote:
Jos Lavrijsen <Jo**********@d iscussions.micr osoft.com> wrote:
When i try to re-use brushes or pens over multiple threads, i often get
an InvalidOperatio nException with the message 'object is currently in use
elsewhere'.
I also tried this by re-using fonts but no problems there.

So, it looks like brushes and pens cannot be used in different threads
simultaneously.
Looks like a dotnet bug to me.


How can it be a bug when it's the documented behaviour, as Larry
pointed out earlier?

Do you really need to be doing UI operations on multiple threads in the
first place? Usually all UI operations should occur on a single thread.
Given the "Philips Medical Systems" bit, I guess you may be writing a
medical imaging application, in which case it's more likely that it's a
reasonable design, but it's worth checking.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too

Dec 21 '05 #4
Jos Lavrijsen <Jo**********@d iscussions.micr osoft.com> wrote:
Ok, brushes may not be thread safe but it feels strange that an exception
is thrown even though i am not modifying the brush.
Apparently, a brush is not only a description but maybe also contains logic
to perform the actual drawing.
I'd expect so, yes. Whatever the reason, it's a UI element.
Drawing on bitmaps has nothing to do with UI operations.
Well, it is in almost all uses, I'd say. Bitmaps are UI elements as far
as Windows is concerned, so you shouldn't access them (or brushes) on
the wrong thread.
In my use-case i am processing a huge amount of images in background to
be exported. To get a high throughput on multiprocessor systems, i use
multiple threads to do this processing.
I try to reuse brushes, fonts and pens to minimize the amount of garbage
produced.


I suggest you cache them by thread instead. You'll still save a lot of
churn, but without violating the WinForms threading principles.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Dec 21 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
11108
by: talljames | last post by:
Has anyone come across this exception before when dealing with C# graphics? Have come across some answers that point to the accelleration control under the screen's properties/settings/advanced/troubleshooting. ie the graphics driver. Other answers include disposing, revalidate. Any suggestions would be appreciated.
4
5021
by: 6tc1 | last post by:
Hi all, I have just finished debugging a windows application and have solved the problem - however, I want to be sure that I understand the problem before I move on. Before I detail the problem, this problem requires some understanding of threading concepts. Basically, the class contained both a PictureBox object as well as a corresponding Image object (they both had a copy of the same picture). The following was used to access the...
1
3234
by: Hadar | last post by:
Hi, I'm getting "object is currently in use elsewhere" when I use System.Drawing.Graphics.MesureString. This is what I do: My controls use a utility class the helps it to mesure strings. To get the best performance for the utility class, its members, as well as the System.Drawing.Graphics object, are static:
8
3561
by: Sharon | last post by:
I have a DataGrid control on a Form. The data of the control is added by another application by Remoting. It means that a worker thread is invoking a UI thread. Therefore I used a delegate in the Form invocation like this: public delegate void AddDefectEventHandler(string xmlDefect); public void AddDefect(string xmlDefect) { this.Invoke(new AddDefectEventHandler(this.AddDefectUI), new object {xmlDefect});
4
5709
by: JJ | last post by:
When I run my form prog, if I maximise, then minimise (i..i. force the GUI to redraw) I get the following error: "The object is currently in use elsewhere" At this line: e.Graphics.DrawString(MenuText.Substring(0, 1), underLinedFont, FontBrush, textLayoutRectangle, sf)
1
2154
by: chad | last post by:
system.InvalidOperationException: the object is currently in use elsewhere... has anyone experienced this error before? I am occasionally getting this error. I can't figure out what could possibly cause it. When the prog runs thru the loop, the error could be thrown anytime. Sometimes it doesn't at all. Seems like it's telling me that the picturebox is in use at the same time that it wants to be updated. But I timed it... displayImg =...
3
2206
by: boeledi | last post by:
Dear All, (First of all this is not a c# piece of code but it does not really matter). I would really appreciate if someone could help me. I am developing an ASP.NET web site and I have to deal with images upload. When the user is selecting an image, I save it as such together with a thumbnail version.
4
2291
by: =?Utf-8?B?Qm9uaQ==?= | last post by:
Hi, I got this problem. I'm implementing a pluggable winform program. My plugins are usercontrol and I load them in my program through a interface. Now if I close my application an error occurs: "Object is currently in use elsewhere". If I comment the line where a I use the Activator.CreateInstance it doesn't happen. I tried to disposed the object created but nothing but If I do a simple new of my object without using reflection it...
0
2329
by: para15000 | last post by:
Hello I have a C# desktop application in which one thread that I create continously gets an image from a source(it's a digital camera actually) and puts it on a panel(panel.Image = img) in the GUI(which must be another thread as it is the code-behind of a control. The application works but on some machines I get the following error at random time
0
9416
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10199
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9849
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8861
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7393
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6661
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5293
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3948
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2810
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.