How to get the target of a weak reference in a safe way





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







8















Consider this code:



var weakRef = new WeakReference(new StringBuilder("Mehran"));
if (weakRef.IsAlive)
{
// Garbage Collection might happen.
Console.WriteLine((weakRef.Target as StringBuilder).ToString());
}


It's possible for GC.Collect to run after checking weakRef.IsAlive and before using the weakRef.Target.



Am I wrong with this? If it's possible, ss there a safe way to do that?



For example an API like weakRef.GetTargetIfIsAlive() would be appropriate.










share|improve this question


















  • 1





    Check out msdn.microsoft.com/en-gb/library/ms404247.aspx

    – Daniel Kelley
    Feb 13 '13 at 15:17






  • 1





    You should first cast to a strong reference and then check for null. There´s no way you can assure your strong reference will not be null beforehand.

    – John Willemse
    Feb 13 '13 at 15:20


















8















Consider this code:



var weakRef = new WeakReference(new StringBuilder("Mehran"));
if (weakRef.IsAlive)
{
// Garbage Collection might happen.
Console.WriteLine((weakRef.Target as StringBuilder).ToString());
}


It's possible for GC.Collect to run after checking weakRef.IsAlive and before using the weakRef.Target.



Am I wrong with this? If it's possible, ss there a safe way to do that?



For example an API like weakRef.GetTargetIfIsAlive() would be appropriate.










share|improve this question


















  • 1





    Check out msdn.microsoft.com/en-gb/library/ms404247.aspx

    – Daniel Kelley
    Feb 13 '13 at 15:17






  • 1





    You should first cast to a strong reference and then check for null. There´s no way you can assure your strong reference will not be null beforehand.

    – John Willemse
    Feb 13 '13 at 15:20














8












8








8


1






Consider this code:



var weakRef = new WeakReference(new StringBuilder("Mehran"));
if (weakRef.IsAlive)
{
// Garbage Collection might happen.
Console.WriteLine((weakRef.Target as StringBuilder).ToString());
}


It's possible for GC.Collect to run after checking weakRef.IsAlive and before using the weakRef.Target.



Am I wrong with this? If it's possible, ss there a safe way to do that?



For example an API like weakRef.GetTargetIfIsAlive() would be appropriate.










share|improve this question














Consider this code:



var weakRef = new WeakReference(new StringBuilder("Mehran"));
if (weakRef.IsAlive)
{
// Garbage Collection might happen.
Console.WriteLine((weakRef.Target as StringBuilder).ToString());
}


It's possible for GC.Collect to run after checking weakRef.IsAlive and before using the weakRef.Target.



Am I wrong with this? If it's possible, ss there a safe way to do that?



For example an API like weakRef.GetTargetIfIsAlive() would be appropriate.







c# .net garbage-collection weak-references






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Feb 13 '13 at 15:15









mehrandvdmehrandvd

4,20783986




4,20783986








  • 1





    Check out msdn.microsoft.com/en-gb/library/ms404247.aspx

    – Daniel Kelley
    Feb 13 '13 at 15:17






  • 1





    You should first cast to a strong reference and then check for null. There´s no way you can assure your strong reference will not be null beforehand.

    – John Willemse
    Feb 13 '13 at 15:20














  • 1





    Check out msdn.microsoft.com/en-gb/library/ms404247.aspx

    – Daniel Kelley
    Feb 13 '13 at 15:17






  • 1





    You should first cast to a strong reference and then check for null. There´s no way you can assure your strong reference will not be null beforehand.

    – John Willemse
    Feb 13 '13 at 15:20








1




1





Check out msdn.microsoft.com/en-gb/library/ms404247.aspx

– Daniel Kelley
Feb 13 '13 at 15:17





Check out msdn.microsoft.com/en-gb/library/ms404247.aspx

– Daniel Kelley
Feb 13 '13 at 15:17




1




1





You should first cast to a strong reference and then check for null. There´s no way you can assure your strong reference will not be null beforehand.

– John Willemse
Feb 13 '13 at 15:20





You should first cast to a strong reference and then check for null. There´s no way you can assure your strong reference will not be null beforehand.

– John Willemse
Feb 13 '13 at 15:20












4 Answers
4






active

oldest

votes


















12














That API already exists; weakRef.Target returns null if the object has already been garbage collected.



StringBuilder sb = weakRef.Target as StringBuilder;
if (sb != null)
{
Console.WriteLine(sb.ToString());
}





share|improve this answer































    9














    The IsAlive property does not exist for the benefit of code which will want to use the target if it is alive, but rather for the benefit of code which wants to find out if the target has died but wouldn't be interested in accessing it in any case. If code were to test Target against null, that would cause Target to momentarily have a strong rooted reference (the code that's testing against null), and it's possible that the act of generating such a rooted reference might prevent the object from being garbage-collected when it otherwise would be. If the code isn't interested in Target except to find out whether it has yet been invalidated, there's no reason for code to get the reference. It can simply test IsAlive instead, and take suitable action if it returns false.






    share|improve this answer
























    • I was wondering why IsAlive exists. This is a very clever answer, Thanks.

      – mehrandvd
      Mar 2 '13 at 5:17






    • 1





      @mehrandvd: It's not hard to imagine a concurrent GC where the act of fetching the Target from a WeakReference would prevent that object from getting collected in the next cycle even if the reference was immediately discarded. On such a system, code which wanted to take some action as soon as an object was no longer needed and used Target rather than IsAlive could end up keeping the object in question alive forever.

      – supercat
      Dec 30 '14 at 19:57



















    1














    Take a local copy of the target and check for null.



    WeakReference.Target will return null if the target has been collected but you're concern is that it's collected between your .IsAlive check and getting the target.



    var weakRef = new WeakReference(new StringBuilder("Mehran"));

    if (weakRef.IsAlive)
    {
    var stringBuilder = weakRef.Target as StringBuilder;

    if (stringBuilder != null)
    {
    Console.WriteLine(stringBuilder.ToString());
    }
    }


    Console.WriteLine((weakRef.Target as StringBuilder).ToString()); will throw a null reference exception if the cast fails.






    share|improve this answer
























    • I was wondering why checking weakRef.IsAlive is required, @supercat answered the question, so I think checking it is not necessary.

      – mehrandvd
      Mar 2 '13 at 5:20






    • 1





      @mehrandvd It might not be necessary, I only used it in this example as it was based upon your original question. It can't do any harm to use it but yes it is possibly a pointless check given the as cast and null check on .Target.

      – Trevor Pilley
      Mar 2 '13 at 9:00






    • 1





      @TrevorPilley: Using IsAlive on a WeakReference if a true value would mean one wants to retrieve the target is pointless. It's possible that with some garbage collectors, using if (wr1.IsAlive && wr2.IsAlive && wr3.IsAlive) {Foo wt1 = wr1.Target as Foo, wt2 = wr2.Target as Foo, wt3 = wr3.Target as Foo; if (wr1 != null && wr2 != null && wr3 != null) {... use all three things...} might be helpful if e.g. a concurrent garbage-collector worked by keeping track of whether a reference to something had been created since the last GC. On such a GC, if wr3 had died but wr1 and wr2 was alive...

      – supercat
      Dec 18 '13 at 19:31



















    0














    I believe what you are looking for is TryGetValue. Your code should look like:



    var weakRef = new WeakReference(new StringBuilder("Mehran"));
    if (weakRef.TryGetValue(out StringBuilder sb)
    {
    Console.WriteLine(sb.ToString());
    }





    share|improve this answer
























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f14856714%2fhow-to-get-the-target-of-a-weak-reference-in-a-safe-way%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      4 Answers
      4






      active

      oldest

      votes








      4 Answers
      4






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      12














      That API already exists; weakRef.Target returns null if the object has already been garbage collected.



      StringBuilder sb = weakRef.Target as StringBuilder;
      if (sb != null)
      {
      Console.WriteLine(sb.ToString());
      }





      share|improve this answer




























        12














        That API already exists; weakRef.Target returns null if the object has already been garbage collected.



        StringBuilder sb = weakRef.Target as StringBuilder;
        if (sb != null)
        {
        Console.WriteLine(sb.ToString());
        }





        share|improve this answer


























          12












          12








          12







          That API already exists; weakRef.Target returns null if the object has already been garbage collected.



          StringBuilder sb = weakRef.Target as StringBuilder;
          if (sb != null)
          {
          Console.WriteLine(sb.ToString());
          }





          share|improve this answer













          That API already exists; weakRef.Target returns null if the object has already been garbage collected.



          StringBuilder sb = weakRef.Target as StringBuilder;
          if (sb != null)
          {
          Console.WriteLine(sb.ToString());
          }






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Feb 13 '13 at 15:17









          Michael LiuMichael Liu

          37k882121




          37k882121

























              9














              The IsAlive property does not exist for the benefit of code which will want to use the target if it is alive, but rather for the benefit of code which wants to find out if the target has died but wouldn't be interested in accessing it in any case. If code were to test Target against null, that would cause Target to momentarily have a strong rooted reference (the code that's testing against null), and it's possible that the act of generating such a rooted reference might prevent the object from being garbage-collected when it otherwise would be. If the code isn't interested in Target except to find out whether it has yet been invalidated, there's no reason for code to get the reference. It can simply test IsAlive instead, and take suitable action if it returns false.






              share|improve this answer
























              • I was wondering why IsAlive exists. This is a very clever answer, Thanks.

                – mehrandvd
                Mar 2 '13 at 5:17






              • 1





                @mehrandvd: It's not hard to imagine a concurrent GC where the act of fetching the Target from a WeakReference would prevent that object from getting collected in the next cycle even if the reference was immediately discarded. On such a system, code which wanted to take some action as soon as an object was no longer needed and used Target rather than IsAlive could end up keeping the object in question alive forever.

                – supercat
                Dec 30 '14 at 19:57
















              9














              The IsAlive property does not exist for the benefit of code which will want to use the target if it is alive, but rather for the benefit of code which wants to find out if the target has died but wouldn't be interested in accessing it in any case. If code were to test Target against null, that would cause Target to momentarily have a strong rooted reference (the code that's testing against null), and it's possible that the act of generating such a rooted reference might prevent the object from being garbage-collected when it otherwise would be. If the code isn't interested in Target except to find out whether it has yet been invalidated, there's no reason for code to get the reference. It can simply test IsAlive instead, and take suitable action if it returns false.






              share|improve this answer
























              • I was wondering why IsAlive exists. This is a very clever answer, Thanks.

                – mehrandvd
                Mar 2 '13 at 5:17






              • 1





                @mehrandvd: It's not hard to imagine a concurrent GC where the act of fetching the Target from a WeakReference would prevent that object from getting collected in the next cycle even if the reference was immediately discarded. On such a system, code which wanted to take some action as soon as an object was no longer needed and used Target rather than IsAlive could end up keeping the object in question alive forever.

                – supercat
                Dec 30 '14 at 19:57














              9












              9








              9







              The IsAlive property does not exist for the benefit of code which will want to use the target if it is alive, but rather for the benefit of code which wants to find out if the target has died but wouldn't be interested in accessing it in any case. If code were to test Target against null, that would cause Target to momentarily have a strong rooted reference (the code that's testing against null), and it's possible that the act of generating such a rooted reference might prevent the object from being garbage-collected when it otherwise would be. If the code isn't interested in Target except to find out whether it has yet been invalidated, there's no reason for code to get the reference. It can simply test IsAlive instead, and take suitable action if it returns false.






              share|improve this answer













              The IsAlive property does not exist for the benefit of code which will want to use the target if it is alive, but rather for the benefit of code which wants to find out if the target has died but wouldn't be interested in accessing it in any case. If code were to test Target against null, that would cause Target to momentarily have a strong rooted reference (the code that's testing against null), and it's possible that the act of generating such a rooted reference might prevent the object from being garbage-collected when it otherwise would be. If the code isn't interested in Target except to find out whether it has yet been invalidated, there's no reason for code to get the reference. It can simply test IsAlive instead, and take suitable action if it returns false.







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Feb 27 '13 at 22:55









              supercatsupercat

              58k3117156




              58k3117156













              • I was wondering why IsAlive exists. This is a very clever answer, Thanks.

                – mehrandvd
                Mar 2 '13 at 5:17






              • 1





                @mehrandvd: It's not hard to imagine a concurrent GC where the act of fetching the Target from a WeakReference would prevent that object from getting collected in the next cycle even if the reference was immediately discarded. On such a system, code which wanted to take some action as soon as an object was no longer needed and used Target rather than IsAlive could end up keeping the object in question alive forever.

                – supercat
                Dec 30 '14 at 19:57



















              • I was wondering why IsAlive exists. This is a very clever answer, Thanks.

                – mehrandvd
                Mar 2 '13 at 5:17






              • 1





                @mehrandvd: It's not hard to imagine a concurrent GC where the act of fetching the Target from a WeakReference would prevent that object from getting collected in the next cycle even if the reference was immediately discarded. On such a system, code which wanted to take some action as soon as an object was no longer needed and used Target rather than IsAlive could end up keeping the object in question alive forever.

                – supercat
                Dec 30 '14 at 19:57

















              I was wondering why IsAlive exists. This is a very clever answer, Thanks.

              – mehrandvd
              Mar 2 '13 at 5:17





              I was wondering why IsAlive exists. This is a very clever answer, Thanks.

              – mehrandvd
              Mar 2 '13 at 5:17




              1




              1





              @mehrandvd: It's not hard to imagine a concurrent GC where the act of fetching the Target from a WeakReference would prevent that object from getting collected in the next cycle even if the reference was immediately discarded. On such a system, code which wanted to take some action as soon as an object was no longer needed and used Target rather than IsAlive could end up keeping the object in question alive forever.

              – supercat
              Dec 30 '14 at 19:57





              @mehrandvd: It's not hard to imagine a concurrent GC where the act of fetching the Target from a WeakReference would prevent that object from getting collected in the next cycle even if the reference was immediately discarded. On such a system, code which wanted to take some action as soon as an object was no longer needed and used Target rather than IsAlive could end up keeping the object in question alive forever.

              – supercat
              Dec 30 '14 at 19:57











              1














              Take a local copy of the target and check for null.



              WeakReference.Target will return null if the target has been collected but you're concern is that it's collected between your .IsAlive check and getting the target.



              var weakRef = new WeakReference(new StringBuilder("Mehran"));

              if (weakRef.IsAlive)
              {
              var stringBuilder = weakRef.Target as StringBuilder;

              if (stringBuilder != null)
              {
              Console.WriteLine(stringBuilder.ToString());
              }
              }


              Console.WriteLine((weakRef.Target as StringBuilder).ToString()); will throw a null reference exception if the cast fails.






              share|improve this answer
























              • I was wondering why checking weakRef.IsAlive is required, @supercat answered the question, so I think checking it is not necessary.

                – mehrandvd
                Mar 2 '13 at 5:20






              • 1





                @mehrandvd It might not be necessary, I only used it in this example as it was based upon your original question. It can't do any harm to use it but yes it is possibly a pointless check given the as cast and null check on .Target.

                – Trevor Pilley
                Mar 2 '13 at 9:00






              • 1





                @TrevorPilley: Using IsAlive on a WeakReference if a true value would mean one wants to retrieve the target is pointless. It's possible that with some garbage collectors, using if (wr1.IsAlive && wr2.IsAlive && wr3.IsAlive) {Foo wt1 = wr1.Target as Foo, wt2 = wr2.Target as Foo, wt3 = wr3.Target as Foo; if (wr1 != null && wr2 != null && wr3 != null) {... use all three things...} might be helpful if e.g. a concurrent garbage-collector worked by keeping track of whether a reference to something had been created since the last GC. On such a GC, if wr3 had died but wr1 and wr2 was alive...

                – supercat
                Dec 18 '13 at 19:31
















              1














              Take a local copy of the target and check for null.



              WeakReference.Target will return null if the target has been collected but you're concern is that it's collected between your .IsAlive check and getting the target.



              var weakRef = new WeakReference(new StringBuilder("Mehran"));

              if (weakRef.IsAlive)
              {
              var stringBuilder = weakRef.Target as StringBuilder;

              if (stringBuilder != null)
              {
              Console.WriteLine(stringBuilder.ToString());
              }
              }


              Console.WriteLine((weakRef.Target as StringBuilder).ToString()); will throw a null reference exception if the cast fails.






              share|improve this answer
























              • I was wondering why checking weakRef.IsAlive is required, @supercat answered the question, so I think checking it is not necessary.

                – mehrandvd
                Mar 2 '13 at 5:20






              • 1





                @mehrandvd It might not be necessary, I only used it in this example as it was based upon your original question. It can't do any harm to use it but yes it is possibly a pointless check given the as cast and null check on .Target.

                – Trevor Pilley
                Mar 2 '13 at 9:00






              • 1





                @TrevorPilley: Using IsAlive on a WeakReference if a true value would mean one wants to retrieve the target is pointless. It's possible that with some garbage collectors, using if (wr1.IsAlive && wr2.IsAlive && wr3.IsAlive) {Foo wt1 = wr1.Target as Foo, wt2 = wr2.Target as Foo, wt3 = wr3.Target as Foo; if (wr1 != null && wr2 != null && wr3 != null) {... use all three things...} might be helpful if e.g. a concurrent garbage-collector worked by keeping track of whether a reference to something had been created since the last GC. On such a GC, if wr3 had died but wr1 and wr2 was alive...

                – supercat
                Dec 18 '13 at 19:31














              1












              1








              1







              Take a local copy of the target and check for null.



              WeakReference.Target will return null if the target has been collected but you're concern is that it's collected between your .IsAlive check and getting the target.



              var weakRef = new WeakReference(new StringBuilder("Mehran"));

              if (weakRef.IsAlive)
              {
              var stringBuilder = weakRef.Target as StringBuilder;

              if (stringBuilder != null)
              {
              Console.WriteLine(stringBuilder.ToString());
              }
              }


              Console.WriteLine((weakRef.Target as StringBuilder).ToString()); will throw a null reference exception if the cast fails.






              share|improve this answer













              Take a local copy of the target and check for null.



              WeakReference.Target will return null if the target has been collected but you're concern is that it's collected between your .IsAlive check and getting the target.



              var weakRef = new WeakReference(new StringBuilder("Mehran"));

              if (weakRef.IsAlive)
              {
              var stringBuilder = weakRef.Target as StringBuilder;

              if (stringBuilder != null)
              {
              Console.WriteLine(stringBuilder.ToString());
              }
              }


              Console.WriteLine((weakRef.Target as StringBuilder).ToString()); will throw a null reference exception if the cast fails.







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Feb 13 '13 at 15:19









              Trevor PilleyTrevor Pilley

              13.9k53553




              13.9k53553













              • I was wondering why checking weakRef.IsAlive is required, @supercat answered the question, so I think checking it is not necessary.

                – mehrandvd
                Mar 2 '13 at 5:20






              • 1





                @mehrandvd It might not be necessary, I only used it in this example as it was based upon your original question. It can't do any harm to use it but yes it is possibly a pointless check given the as cast and null check on .Target.

                – Trevor Pilley
                Mar 2 '13 at 9:00






              • 1





                @TrevorPilley: Using IsAlive on a WeakReference if a true value would mean one wants to retrieve the target is pointless. It's possible that with some garbage collectors, using if (wr1.IsAlive && wr2.IsAlive && wr3.IsAlive) {Foo wt1 = wr1.Target as Foo, wt2 = wr2.Target as Foo, wt3 = wr3.Target as Foo; if (wr1 != null && wr2 != null && wr3 != null) {... use all three things...} might be helpful if e.g. a concurrent garbage-collector worked by keeping track of whether a reference to something had been created since the last GC. On such a GC, if wr3 had died but wr1 and wr2 was alive...

                – supercat
                Dec 18 '13 at 19:31



















              • I was wondering why checking weakRef.IsAlive is required, @supercat answered the question, so I think checking it is not necessary.

                – mehrandvd
                Mar 2 '13 at 5:20






              • 1





                @mehrandvd It might not be necessary, I only used it in this example as it was based upon your original question. It can't do any harm to use it but yes it is possibly a pointless check given the as cast and null check on .Target.

                – Trevor Pilley
                Mar 2 '13 at 9:00






              • 1





                @TrevorPilley: Using IsAlive on a WeakReference if a true value would mean one wants to retrieve the target is pointless. It's possible that with some garbage collectors, using if (wr1.IsAlive && wr2.IsAlive && wr3.IsAlive) {Foo wt1 = wr1.Target as Foo, wt2 = wr2.Target as Foo, wt3 = wr3.Target as Foo; if (wr1 != null && wr2 != null && wr3 != null) {... use all three things...} might be helpful if e.g. a concurrent garbage-collector worked by keeping track of whether a reference to something had been created since the last GC. On such a GC, if wr3 had died but wr1 and wr2 was alive...

                – supercat
                Dec 18 '13 at 19:31

















              I was wondering why checking weakRef.IsAlive is required, @supercat answered the question, so I think checking it is not necessary.

              – mehrandvd
              Mar 2 '13 at 5:20





              I was wondering why checking weakRef.IsAlive is required, @supercat answered the question, so I think checking it is not necessary.

              – mehrandvd
              Mar 2 '13 at 5:20




              1




              1





              @mehrandvd It might not be necessary, I only used it in this example as it was based upon your original question. It can't do any harm to use it but yes it is possibly a pointless check given the as cast and null check on .Target.

              – Trevor Pilley
              Mar 2 '13 at 9:00





              @mehrandvd It might not be necessary, I only used it in this example as it was based upon your original question. It can't do any harm to use it but yes it is possibly a pointless check given the as cast and null check on .Target.

              – Trevor Pilley
              Mar 2 '13 at 9:00




              1




              1





              @TrevorPilley: Using IsAlive on a WeakReference if a true value would mean one wants to retrieve the target is pointless. It's possible that with some garbage collectors, using if (wr1.IsAlive && wr2.IsAlive && wr3.IsAlive) {Foo wt1 = wr1.Target as Foo, wt2 = wr2.Target as Foo, wt3 = wr3.Target as Foo; if (wr1 != null && wr2 != null && wr3 != null) {... use all three things...} might be helpful if e.g. a concurrent garbage-collector worked by keeping track of whether a reference to something had been created since the last GC. On such a GC, if wr3 had died but wr1 and wr2 was alive...

              – supercat
              Dec 18 '13 at 19:31





              @TrevorPilley: Using IsAlive on a WeakReference if a true value would mean one wants to retrieve the target is pointless. It's possible that with some garbage collectors, using if (wr1.IsAlive && wr2.IsAlive && wr3.IsAlive) {Foo wt1 = wr1.Target as Foo, wt2 = wr2.Target as Foo, wt3 = wr3.Target as Foo; if (wr1 != null && wr2 != null && wr3 != null) {... use all three things...} might be helpful if e.g. a concurrent garbage-collector worked by keeping track of whether a reference to something had been created since the last GC. On such a GC, if wr3 had died but wr1 and wr2 was alive...

              – supercat
              Dec 18 '13 at 19:31











              0














              I believe what you are looking for is TryGetValue. Your code should look like:



              var weakRef = new WeakReference(new StringBuilder("Mehran"));
              if (weakRef.TryGetValue(out StringBuilder sb)
              {
              Console.WriteLine(sb.ToString());
              }





              share|improve this answer




























                0














                I believe what you are looking for is TryGetValue. Your code should look like:



                var weakRef = new WeakReference(new StringBuilder("Mehran"));
                if (weakRef.TryGetValue(out StringBuilder sb)
                {
                Console.WriteLine(sb.ToString());
                }





                share|improve this answer


























                  0












                  0








                  0







                  I believe what you are looking for is TryGetValue. Your code should look like:



                  var weakRef = new WeakReference(new StringBuilder("Mehran"));
                  if (weakRef.TryGetValue(out StringBuilder sb)
                  {
                  Console.WriteLine(sb.ToString());
                  }





                  share|improve this answer













                  I believe what you are looking for is TryGetValue. Your code should look like:



                  var weakRef = new WeakReference(new StringBuilder("Mehran"));
                  if (weakRef.TryGetValue(out StringBuilder sb)
                  {
                  Console.WriteLine(sb.ToString());
                  }






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 16 '18 at 22:55









                  Огњен ШобајићОгњен Шобајић

                  770823




                  770823






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f14856714%2fhow-to-get-the-target-of-a-weak-reference-in-a-safe-way%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Xamarin.iOS Cant Deploy on Iphone

                      Glorious Revolution

                      Dulmage-Mendelsohn matrix decomposition in Python