当前位置: 首页>>代码示例>>C#>>正文


C# WeakReference.TryGetTarget方法代码示例

本文整理汇总了C#中System.WeakReference.TryGetTarget方法的典型用法代码示例。如果您正苦于以下问题:C# WeakReference.TryGetTarget方法的具体用法?C# WeakReference.TryGetTarget怎么用?C# WeakReference.TryGetTarget使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.WeakReference的用法示例。


在下文中一共展示了WeakReference.TryGetTarget方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Into

        /// <summary>
        /// Loads the image into given imageView using defined parameters.
        /// </summary>
        /// <param name="parameters">Parameters for loading the image.</param>
        /// <param name="imageView">Image view that should receive the image.</param>
        /// <param name="imageScale">Optional scale factor to use when interpreting the image data. If unspecified it will use the device scale (ie: Retina = 2, non retina = 1)</param>
        public static IScheduledWork Into(this TaskParameter parameters, UIImageView imageView, float imageScale = -1f)
        {
            var weakRef = new WeakReference<UIImageView>(imageView);
            Func<UIImageView> getNativeControl = () => {
                UIImageView refView;
                if (!weakRef.TryGetTarget(out refView))
                    return null;
                return refView;
            };

			Action<UIImage, bool> doWithImage = (img, fromCache) => {
                UIImageView refView = getNativeControl();
                if (refView == null)
                    return;

				var isFadeAnimationEnabled = parameters.FadeAnimationEnabled.HasValue ? 
					parameters.FadeAnimationEnabled.Value : ImageService.Config.FadeAnimationEnabled;

				if (isFadeAnimationEnabled && !fromCache)
				{
					// fade animation
					UIView.Transition(refView, 0.4f, 
						UIViewAnimationOptions.TransitionCrossDissolve 
						| UIViewAnimationOptions.BeginFromCurrentState,
						() => { refView.Image = img; },
						() => {  });
				}
				else
				{
					refView.Image = img;
				}
            };

            return parameters.Into(getNativeControl, doWithImage, imageScale);
        }
开发者ID:nukedbit,项目名称:FFImageLoading,代码行数:41,代码来源:TaskParameterExtensions.cs

示例2: LayoutTo

		public static Task<bool> LayoutTo(this VisualElement view, Rectangle bounds, uint length = 250, Easing easing = null)
		{
			if (view == null)
				throw new ArgumentNullException("view");
			if (easing == null)
				easing = Easing.Linear;

			var tcs = new TaskCompletionSource<bool>();
			Rectangle start = view.Bounds;
			Func<double, Rectangle> computeBounds = progress =>
			{
				double x = start.X + (bounds.X - start.X) * progress;
				double y = start.Y + (bounds.Y - start.Y) * progress;
				double w = start.Width + (bounds.Width - start.Width) * progress;
				double h = start.Height + (bounds.Height - start.Height) * progress;

				return new Rectangle(x, y, w, h);
			};
			var weakView = new WeakReference<VisualElement>(view);
			Action<double> layout = f =>
			{
				VisualElement v;
				if (weakView.TryGetTarget(out v))
					v.Layout(computeBounds(f));
			};
			new Animation(layout, 0, 1, easing).Commit(view, "LayoutTo", 16, length, finished: (f, a) => tcs.SetResult(a));

			return tcs.Task;
		}
开发者ID:Costo,项目名称:Xamarin.Forms,代码行数:29,代码来源:ViewExtensions.cs

示例3: TranslateXTo

        public static Task<bool> TranslateXTo(this VisualElement view, double x, 
                                              uint length = 250, Easing easing = null) 
        { 
            easing = easing ?? Easing.Linear; 
 	        TaskCompletionSource<bool> taskCompletionSource = new TaskCompletionSource<bool>();
            WeakReference<VisualElement> weakViewRef = new WeakReference<VisualElement>(view);

            Animation animation = new Animation(
                (value) => 
                    {
                        VisualElement viewRef;
                        if (weakViewRef.TryGetTarget(out viewRef))
                        {
                            viewRef.TranslationX = value;
                        }
                    },              // callback
                view.TranslationX,  // start
                x,                  // end
                easing);            // easing

            animation.Commit(
                view,               // owner
                "TranslateXTo",     // name
                16,                 // rate
                length,             // length
                null,               // easing 
                (finalValue, cancelled) => 
                        taskCompletionSource.SetResult(cancelled)); // finished
 			 
 	        return taskCompletionSource.Task; 
        } 
开发者ID:xia101,项目名称:xamarin-forms-book-samples,代码行数:31,代码来源:MoreViewExtensions.cs

示例4: FlowListViewInternalCell

		/// <summary>
		/// Initializes a new instance of the <see cref="DLToolkit.Forms.Controls.FlowListViewInternalCell"/> class.
		/// </summary>
		/// <param name="flowListViewRef">Flow list view reference.</param>
		public FlowListViewInternalCell(WeakReference<FlowListView> flowListViewRef)
		{
			_flowListViewRef = flowListViewRef;
			FlowListView flowListView = null;
			flowListViewRef.TryGetTarget(out flowListView);
			_useGridAsMainRoot = !flowListView.FlowUseAbsoluteLayoutInternally;

			if (!_useGridAsMainRoot)
			{
				_rootLayout = new AbsoluteLayout()
				{
					Padding = 0d,
					BackgroundColor = flowListView.FlowRowBackgroundColor,
				};
				View = _rootLayout;
			}
			else
			{
				_rootLayoutAuto = new Grid()
				{
					RowSpacing = 0d,
					ColumnSpacing = 0d,
					Padding = 0d,
					BackgroundColor = flowListView.FlowRowBackgroundColor,
				};
				View = _rootLayoutAuto;
			}

			_flowColumnTemplate = flowListView.FlowColumnTemplate;
			_desiredColumnCount = flowListView.DesiredColumnCount;
			_flowColumnExpand = flowListView.FlowColumnExpand;
		}
开发者ID:daniel-luberda,项目名称:DLToolkit.Forms.Controls,代码行数:36,代码来源:FlowListViewInternalCell.cs

示例5: Main

        static void Main(string[] args) {
            var appBuilder = new AppBuilder();
            Nowin.OwinServerFactory.Initialize(appBuilder.Properties);

            appBuilder.Use<ConsoleLogMiddleware>();

            appBuilder.Use<SimpleStaticFileMiddleWare>(System.IO.Path.Combine(Environment.CurrentDirectory, @"../../www"));

            var startup = new WebApi.Startup();
            startup.Configuration(appBuilder);

            var builder = new Nowin.ServerBuilder();
            const string ip = "127.0.0.1";
            const int port = 8888;
            builder.SetAddress(System.Net.IPAddress.Parse(ip)).SetPort(port)
                .SetOwinApp(appBuilder.Build())
                .SetOwinCapabilities((IDictionary<string, object>)appBuilder.Properties[Nowin.OwinKeys.ServerCapabilitiesKey]);

            using (var server = builder.Build()) {

                var serverRef = new WeakReference<Nowin.INowinServer>(server);

                Task.Run(() => {
                    Nowin.INowinServer nowinServer;
                    if (serverRef.TryGetTarget(out nowinServer)) {
                        nowinServer.Start();
                    }
                });

                var baseAddress = "http://" + ip + ":" + port + "/";
                Console.WriteLine("Nowin server listening {0}, press ENTER to exit.", baseAddress);

                Console.ReadLine();
            }
        }
开发者ID:beginor,项目名称:practice,代码行数:35,代码来源:Program.cs

示例6: Into

        /// <summary>
        /// Loads the image into given imageView using defined parameters.
        /// </summary>
        /// <param name="parameters">Parameters for loading the image.</param>
        /// <param name="imageView">Image view that should receive the image.</param>
        public static IScheduledWork Into(this TaskParameter parameters, Image imageView)
        {
            var weakRef = new WeakReference<Image>(imageView);

            Func<Image> getNativeControl = () => {
                Image refView = null;

                if (!weakRef.TryGetTarget(out refView))
                    return null;

                return refView;
            };

            Action<WriteableBitmap, bool, bool> doWithImage = (img, isLocalOrFromCache, isLoadingPlaceholder) => {
                Image refView = getNativeControl();
                if (refView == null)
                    return;

                bool imageChanged = (img != refView.Source);
                if (!imageChanged)
                    return;

                bool isFadeAnimationEnabled = parameters.FadeAnimationEnabled.HasValue ?
                    parameters.FadeAnimationEnabled.Value : ImageService.Config.FadeAnimationEnabled;

                bool isFadeAnimationEnabledForCached = isFadeAnimationEnabled && (parameters.FadeAnimationForCachedImages.HasValue ?
                    parameters.FadeAnimationForCachedImages.Value : ImageService.Config.FadeAnimationForCachedImages);

                if (!isLoadingPlaceholder && isFadeAnimationEnabled && (!isLocalOrFromCache || (isLocalOrFromCache && isFadeAnimationEnabledForCached)))
                {
                    // fade animation
                    int fadeDuration = parameters.FadeAnimationDuration.HasValue ?
                        parameters.FadeAnimationDuration.Value : ImageService.Config.FadeAnimationDuration;
                    DoubleAnimation fade = new DoubleAnimation();
                    fade.Duration = TimeSpan.FromMilliseconds(fadeDuration);
					fade.From = 0f;
					fade.To = 1f;
					fade.EasingFunction = new CubicEase() { EasingMode = EasingMode.EaseInOut }; 

					Storyboard fadeInStoryboard = new Storyboard();

#if SILVERLIGHT
                    Storyboard.SetTargetProperty(fade, new PropertyPath("Image.Opacity"));
#else
                    Storyboard.SetTargetProperty(fade, "Image.Opacity");
#endif
                    Storyboard.SetTarget(fade, refView);
					fadeInStoryboard.Children.Add(fade);
					fadeInStoryboard.Begin();
					refView.Source = img;
                }
                else
                {
                    refView.Source = img;
                }
            };

            return parameters.Into(getNativeControl, doWithImage);
        }
开发者ID:petlack,项目名称:FFImageLoading,代码行数:64,代码来源:TaskParameterExtensions.cs

示例7: BusyContext

            public BusyContext(ViewModelBase viewModel)
            {
                _weakViewModelRef = new WeakReference<ViewModelBase>(viewModel);

                ViewModelBase target;
                if (_weakViewModelRef.TryGetTarget(out target))
                    target.IsBusy = true;
            }
开发者ID:Cybrosys,项目名称:Sandbox,代码行数:8,代码来源:ViewModelBase.cs

示例8: UpdateValueChanged

 private static EventHandler UpdateValueChanged(WeakReference<BooleanElement> weakThis)
 {
     return new EventHandler((s, _) => {
         BooleanElement parent;
         if (weakThis.TryGetTarget(out parent))
             parent.Value = ((UISwitch)s).On;
     });
 }
开发者ID:runt18,项目名称:CodeHub,代码行数:8,代码来源:TrueFalseElement.cs

示例9: Main

        static void Main(string[] args)
        {
            var a = new object();
            var wa = new WeakReference<object>(a);

            object refa;
            if (wa.TryGetTarget(out refa))
            {
                Console.WriteLine("refa find");
            }
            else
            {
                Console.WriteLine("refa lose");
            }

            a = null;
            a = null;
            a = null;
            a = null;
            System.Threading.Thread.Sleep(1000);
            System.GC.Collect();
            System.Threading.Thread.Sleep(1000);

            if (refa != null)
            {
                Console.WriteLine("refa find");
            }
            else
            {
                Console.WriteLine("refa lose");
            }

            if (wa.TryGetTarget(out refa))
            {
                Console.WriteLine("refa find");
            }
            else
            {
                Console.WriteLine("refa lose");
            }

            Console.ReadKey();
            TestRequester();
        }
开发者ID:jiowchern,项目名称:Regulus,代码行数:44,代码来源:Program.cs

示例10: UntrackedDisposablesAreNotTracked

        public void UntrackedDisposablesAreNotTracked()
        {
            var resolver = new DefaultDependencyResolver();
            resolver.Register(typeof(MyUntrackedDisposable), () => new MyUntrackedDisposable());

            var untrackedDisposable = resolver.Resolve<MyUntrackedDisposable>();
            var untrackedDisposableWeakRef = new WeakReference<MyUntrackedDisposable>(untrackedDisposable);
            
            untrackedDisposable = null;
            GC.Collect();
            GC.WaitForPendingFinalizers();
            Assert.False(untrackedDisposableWeakRef.TryGetTarget(out untrackedDisposable));
        }
开发者ID:Choulla-Naresh8264,项目名称:SignalR,代码行数:13,代码来源:DefaultDependencyResolverFacts.cs

示例11: ActivateWith

 /// <summary>
 /// Activate the child whenever the parent is activated
 /// </summary>
 /// <example>child.ActivateWith(this)</example>
 /// <param name="child">Child to activate whenever the parent is activated</param>
 /// <param name="parent">Parent to observe</param>
 public static void ActivateWith(this IScreenState child, IScreenState parent)
 {
     var weakChild = new WeakReference<IScreenState>(child);
     EventHandler<ActivationEventArgs> handler = null;
     handler = (o, e) =>
     {
         IScreenState strongChild;
         if (weakChild.TryGetTarget(out strongChild))
             strongChild.Activate();
         else
             parent.Activated -= handler;
     };
     parent.Activated += handler;
 }
开发者ID:modulexcite,项目名称:Stylet,代码行数:20,代码来源:ScreenExtensions.cs

示例12: ItShouldBePossibileToAbandonAnEnumerationWithoutLeaking

        public async Task ItShouldBePossibileToAbandonAnEnumerationWithoutLeaking()
        {
            var outerReference = new Uri("http://tempuri.org");

            //var enumerable = EnumerableStateMachine(outerReference);
            //enumerable.Take(10).ToList();



            var probeWeakReference = new WeakReference<Uri>(outerReference);
            var sequence = AsyncEnumerable.Create<string>(async p =>
            {
                // This will be hoisted in the state machine that is generated 
                // by the compiler.
                Uri hoistedReference;
                Assert.IsTrue(probeWeakReference.TryGetTarget(out hoistedReference));
                int i = 0;
                while (true)
                {
                    await // This will register a callback that reference 
                          // this state machine on the threadpool, that in 
                          // turn will keep alive the instance referenced 
                          // by `hoistedReference`
                        p.Yield(hoistedReference.ToString() + i++);
                }
            });

            // Just a sanity check to verify that the state machine has been created and did what we expected.
            var expectedList = Enumerable.Range(0, 10).Select(i => outerReference.ToString() + i).ToList();
            var asyncList = await sequence.Take(10).ToList();
            CollectionAssert.AreEqual(expectedList, (ICollection)asyncList);


            // Release our reference to the Uri.
            // If the continuation that point to the next step in the asynchronous state machine has not 
            // been removed from the thread pool queue, weakReference.Target  will not be null after the 
            // GC run.
            outerReference = null;

            GC.Collect(2, GCCollectionMode.Forced, true);
            GC.WaitForPendingFinalizers();

            Uri unused;
            Assert.IsFalse(
                probeWeakReference.TryGetTarget(out unused),
                "The reference to the Uri should have been collected.\r\n" +
                "This probably means that the state machine has not been properly disposed and " +
                "is still keep alive by one or more references in the thread pool."
            );
        }
开发者ID:D3-LucaPiombino,项目名称:ALinq,代码行数:50,代码来源:AsyncEnumerableTests.cs

示例13: HubReferencesAreNotRetained

        public void HubReferencesAreNotRetained()
        {
            var resolver = new DefaultDependencyResolver();
            resolver.Register(typeof(DontLeakMeHub), () => new DontLeakMeHub());

            var hub = resolver.Resolve<DontLeakMeHub>();
            Assert.NotNull(hub);

            var hubWeakRef = new WeakReference<DontLeakMeHub>(hub);
            hub.Dispose();
            hub = null;
            GC.Collect();
            GC.WaitForPendingFinalizers();
            Assert.False(hubWeakRef.TryGetTarget(out hub));
        }
开发者ID:Choulla-Naresh8264,项目名称:SignalR,代码行数:15,代码来源:DefaultDependencyResolverFacts.cs

示例14: StartLoop

        // 1秒に1回、「参照中」メッセージを表示
        static async Task StartLoop(WeakReference<object> r)
        {
            while (true)
            {
                object obj;
                if (r.TryGetTarget(out obj))
                {
                    Console.WriteLine(obj + " を参照中");
                }
                else
                {
                    Console.WriteLine("参照がなくなりました");
                    break;
                }

                await Task.Delay(1000);
            }
        }
开发者ID:ufcpp,项目名称:UfcppSample,代码行数:19,代码来源:Program.cs

示例15: CreateCallback

 private static EventHandler<NavigationEventArgs> CreateCallback(WeakReference<ICancellableViewModel> viewModelHandle, WeakReference<IPageLifetimeCallback> pageHandle)
 {
     EventHandler<NavigationEventArgs> callback = null;
     callback = (sender, e) =>
     {
         ICancellableViewModel viewModel;
         IPageLifetimeCallback page;
         if (pageHandle.TryGetTarget(out page))
         {
             page.NavigatedFrom -= callback;
         }
         if (viewModelHandle.TryGetTarget(out viewModel))
         {
             viewModel.Cancel();
         }
     };
     return callback;
 }
开发者ID:Opiumtm,项目名称:DvachBrowser3,代码行数:18,代码来源:PageLifetimeHelper.cs


注:本文中的System.WeakReference.TryGetTarget方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。