本文整理汇总了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);
}
示例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;
}
示例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;
}
示例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;
}
示例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();
}
}
示例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);
}
示例7: BusyContext
public BusyContext(ViewModelBase viewModel)
{
_weakViewModelRef = new WeakReference<ViewModelBase>(viewModel);
ViewModelBase target;
if (_weakViewModelRef.TryGetTarget(out target))
target.IsBusy = true;
}
示例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;
});
}
示例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();
}
示例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));
}
示例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;
}
示例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."
);
}
示例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));
}
示例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);
}
}
示例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;
}