C# WeakReference Example
How would you like to be able to write the programming equivalent of “I might need this later….but I’m not so sure”? I’ll show you how.
A WeakReference is an object with a very interesting behavior, it allows you to keep a reference to an object while still making it possible for it to be garbage collected. See a previous post for a little more detail and links. Internally the WeakReference type uses an IntPtr to track a GCHandle that was acquired using the GCHandleType of Weak or WeakTrackResurrection.
This can be very useful if you are trying to managing the lifetime of objects in a cache or adding optimizations to possibly save time by not having to recreate an expensive object.
Let’s look at an example.
In your class you created two member variables:
WeakReference _weakRef = null;
Person _strongRef = null;
You created two new Person objects (which are simple objects I just created for this example, consisting of a Name property and some reference tracking code). Next you set the member variables to the newly created instances of the Person objects.
_strongRef = p;
_weakRef = new WeakReference(p1);
The difference here you’ll notice that _strongRef is just a regular normal reference, whereas _weakRef is set to a WeakReference object with the person object (p1) passed in as a parameter in the constructor.
If a garbage collection were to occur, or just for testing purposes you called it yourself with:
GC.Collect();
Then the p1 target object that is held by the _weakRef member variable should be garbage collected. You can write code to check:
if (_weakRef.IsAlive)
If the WeakReference is still alive you can convert the WeakReference to a strong or normal reference by using code like this:
Person p = _weakRef.Target as Person;
Now the p reference is treated as a strong reference and won’t be collected until it is no longer used. If you wanted to keep the reference around after the scope you could set that to a member variable.
There aren’t many times in programming that you get to say “maybe”. It’s usually binary — 1 or 0. A WeakReference seems to be one of them.
Ruby On Rails Blog Written by .NET Developers
I found a very interesting blog called “Softies On Rails” that is written by two developers who have spent a lot of time developing software using Microsoft .NET.
Here are a few of my favorite posts on their blog:
Rails IDE for Windows after reading this post I downloaded the IDE and it’s like a mini version of Visual Studio just for Ruby On Rails — pretty cool.
Why Rails? Part 5: Because I can test it
Overall a very interesting blog. Subscribed! And good luck with your new venture guys!
RubyCLR
If you have ready my previous posts you know I am learning the Ruby language and the Rails web application framework.
I saw this post on blogs.msdn.com by Tim Ng that provides details on using RubyCLR to call VB.NET methods from Ruby which seems pretty straightforward and calling Ruby from VB.NET which is more complex.
Between the IronPython project and now RubyCLR it open’s up some interesting possibilities for using the power of dynamic languages in .NET.
10 Cool Features of the Google Search Box
Here is my entry for the latest Problogger Group Writing Project. If you would like to participate too, you can submit your entry before the end of the day Thursday August 17th.
I wanted to write about something that I thought would be very useful to anyone who uses the web. The search box on Google has some neat features in addition to searching. Here are my favorites:
- Calculator - performs math and conversions
- URL Information - find out what sites link to a url
- Definitions - provides the definition of the word entered
- Phone Number Lookup - you can look up residential and business phone numbers
- Answers - you can enter in fact based questions and Google returns the answers
- Site specific searches - if you enter a site:url then your search results are restricted to just that site
- Stock quotes - enter a ticker and get a stock quote including a chart
- Weather
- Map Info
- Movies - display movie information for a given location or zip code
To see the whole list of Google search features visit their help center.
Visual Studio Keyboard Tip #6 - Find Window Command Line
There’s a great feature hidden in the Find Window Combo Box that is part of the standard Toolbar in Visual Studio.
- Open Visual Studio
- CTRL + N (Create a new file) choose “HTML Page”
- Position the cursor on the tag
- Press CTRL + /
- The focus should have shifted to the Find Combo Box
- Type >
- Now type E
- Cool! It’s a command line with built in Intellisense.
- Type dit.LineT
- The entry for Edit.LineTranspose should be selected
- Press enter
You’ll notice that the
and tags are now transposed. Take a few minutes to look around at what commands are available in this list. You can browse the list by entering one letter at a time. For example “>a” to see all the items that begin with a.This is a great way to quickly execute commands that aren’t mapped to convenient keyboard shortcuts.
Really powerful debugging with WinDBG & SOS.dll
If you have never used WinDBG or the SOS extensions before, read the following blog posts by Mike Taulty:
Mike walks you through a sample debugging session with WinDBG. Then in the second part, he focuses on the SOS extensions for .NET debugging. With the SOS extension you can do some seriously cool stuff:
- View thread/threadpool info
- View the finalizequeue
- See what’s allocated on the managed heap
- Determine what is keeping your managed object from being finalized by viewing it’s “roots”
If you have Visual C++ installed you can actually use SOS calls from the Visual Studio debugger! Read Mike’s post, that walks you through the setup and use of SOS from inside Visual Studio. As Mike points out, make sure you go to the project properties, choose Debug, and then check “Enabled unmanaged code debugging”. Be prepared the very first time you do this, it might be slow because the symbols have to be downloaded/loaded.
Ruby On Rails - Part Four - Rake
I have always been interested in automating common development tasks. I have used Ant, Maven, and Nant pretty extensively and now I’m learning the details of Rake. There’s something special about seeing messages fly by in a command shell, and know that the computer is doing all these repetitive tasks — not you!
What is different about Rake then any of the others build tools mentioned is that you create a Rakefile by writing Ruby code, instead of using xml. There is a
I would recommend you read this excellent article on defmacro.org (take your time and read through it — it’s really worth it) that does a good job of explaining the benefits of Lisp. A cool thing, since we’re talking about build automation, is one section, titled “Ant Reloaded”, talks about how Java could have been used instead of XML. In our case it’s Ruby being used in a Rakefile.
This tutorial is written by the developer of Rake, and is a good tour through the main features of Rake. I would suggest you read it first, followed by this article by Martin Fowler which reviews some examples of interesting things you can do with a Rakefile.
I created a simple example Rakefile. I’m sure no one would actually need a script like this, but the simple scenario was good for an example of how to use Rake.
I’ve included the code below, the formatting is off because I pasted it in my blog editor, but I hope it will be a good example to someone just getting started with Rake. If you have any suggestions on how to improve this simple Rakefile example, please add a comment to this post.
# ———————————————————-
# This is just an example to illustrate how to use Rake
# By Rob Herbst
# ———————————————————-
# Require rake/clean to get the built in clean task
require ‘rake/clean’
# Require ftools to get File.copy
require ‘ftools’
# Define constants we’ll use later
HTML_SRC_DIR = “html”
WEB_DEST_DIR = “website”
IMAGES_DIR = “images”
SITE_MAP = “sitemap.html”
HTML_SRC_FILES = FileList[“#{HTML_SRC_DIR}/*.html”]
IMAGE_SRC_FILES = FileList[“#{HTML_SRC_DIR}/*.jpg”]
# Add the WEB_DEST_DIR to the list to get cleaned
CLEAN.include(WEB_DEST_DIR)
# The default task depends upon the package task
task :default => [:package]
# The package task depends upon clean, create structure, and the task to create the site map file.
task :package => [:clean, :create_structure, :sitemap] do
puts “The package task was called.”
# Copy over the html files
HTML_SRC_FILES.each do |f|
File.copy(“#{f}”, “#{WEB_DEST_DIR}”)
end
# Copy over the image files
IMAGE_SRC_FILES.each do |f|
File.copy(“#{f}”, “#{WEB_DEST_DIR}/images”)
end
end
# Utility task to create the structure of the website
task :create_structure do
puts “The create_structure task was called.”
Dir.mkdir(WEB_DEST_DIR)
Dir.chdir(WEB_DEST_DIR)
Dir.mkdir(IMAGES_DIR)
Dir.chdir(“..”)
end
# Task to create the sitemap.html file
task: :sitemap do
open(“#{WEB_DEST_DIR}/#{SITE_MAP}”, “w”) do |outs|
outs.puts “<html><head>Site Map</head><body><ul>”
HTML_SRC_FILES.each do |f|
file_name = f.sub(HTML_SRC_DIR + “/”, “”)
outs.puts “<li><a href=\”#{file_name}\”>#{file_name}</></li>”
end
outs.puts “</ul></body>”
end
end
Team Foundation Server Project Guidance
Eric Lee’s blog post provides some guidance into how Microsoft sets up the Areas for a Team Project in Visual Studio Team System.
I know this has been a source of a little bit of confusion for TFS users, so it’s nice to see an example of how Microsoft is using the feature internally.
Thanks for the post Eric, would it be possible for you to show us an example of how you setup the Iteration tab too?
Google Rss Reader is very cool
I have recently switched my RSS aggregator to Google Reader. This app is still officially in the Google Labs environment, so once in a while there will be a slight hiccup. But, overall I have found this to be a great rss reader.
It has full keyboard support!
- J to move down article list
- K to move up article list
- SPACE to page through a long post, then when the end is reached it moves to the next unread item in your list
It also has support for tags or categories, or labels as Google calls them, which comes in handy if you want to categorize your feeds. You can also share your “starred” items, this feature I have not checked out yet, but it seems interesting.
If you go to the familiar Google search box at the top, it allows you to search for new blogs on a topic. For example, go to the search box at the top, enter “Rob Herbst”, then hit the button labeled “Search for new content”. Now click on the subscribe button….only kidding.
Google Reader also supports mobile devices, which is great if you have to catch up on your feeds on the go.
This post on the Google Reader Blog reviews a sample of what the top errors in the xml feeds that the development team sees. Pretty interesting to see the number two is mismatched tags!
Overall, I think this is a great rss reader that is definitely worth checking out.
Update 8/11:
My friends Pete and Nick don’t like Google Reader. I guess it all comes down to your personal workflow. I used to read my blogs in a similar fashion but that just didn’t work for me. I realized that I had subscribed to way too many blogs, and there was no way I was ever going to have time to read them all. I’m glad that method works for Pete & Nick.
Actually, looking at all those unread items in my Newsgator/Outlook newsreader made me feel like I wasn’t able to keep up — very unmotivating for me. So what I did was to radically trim down the number of feeds that I read. It was difficult to do, but I tried to look at each one and really determine if I was really getting any value from it.
I was able to cut my subscribed list down to just a handful, so the approach that Google Reader takes works perfectly fine for me. I only get about 15-20 new posts per day, so cruising through them in the one place is okay with me. I guess, it also resonates with my Getting Things Done experience. With this approach I have an inbox, where I process the items one at a time. I understand that if you have a much larger & varied subscription list this approach doesn’t seem to work well.
As for keeping entries for future reference, you can either “star” them, or inside the view when you are reading the item, you can check the “keep unread” and it will be displayed until you manually clear it.
I do have to say I was on the train today and I was very happy being able to read my blog entries on my smartphone (which is true of any server based aggregator). That was very cool!
Anyway, Pete & Nick, I’m sorry you guys don’t like Google Reader, but like I mentioned at the top I think it all comes down to personal workflow in how you read your feeds. Both of you seem to have a similar approach were a tool like BlogLines or Newsgator is a better fit.