Weak reference benefits

前端 未结 3 1127
悲&欢浪女
悲&欢浪女 2020-11-30 21:00

Can someone explain the main benefits of different types of references in C#?

  • Weak references
  • Soft references
  • Phantom references
  • Str
3条回答
  •  北海茫月
    2020-11-30 21:50

    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

提交回复
热议问题