Can someone explain the main benefits of different types of references in C#?
Brilliant real example with WeakReference is explained in Android development tutorial.
There is an image (Bitmap) and image container on the view (ImageView). If image will be loaded not from memory (but e.g. from disk, net) then it can lock UI thread and the screen. To avoid it an async task can be used.
The problem arises when async task finishes. Image container can be not useful at all at that time (screen is changed or Android unloads invisible view part after scrolling). WeakReference can help here and ImageView will be garbage collected.
class BitmapWorkerTask extends AsyncTask {
private final WeakReference imageViewReference;
public BitmapWorkerTask(ImageView imageView) {
imageViewReference = new WeakReference(imageView);
}
// Method for getting bitmap is removed for code clearness
// Once complete, see if ImageView is still around and set bitmap.
@Override
protected void onPostExecute(Bitmap bitmap) {
if (imageViewReference != null && bitmap != null) {
final ImageView imageView = imageViewReference.get();
if (imageView != null) {
imageView.setImageBitmap(bitmap);
}
}
}
}
P.S. the example is in Java, but can be understood by C# developers.
Source: http://developersdev.blogspot.ru/2014/01/weakreference-example.html