本文整理汇总了C#中System.Windows.Threading.Dispatcher.CheckAccess方法的典型用法代码示例。如果您正苦于以下问题:C# Dispatcher.CheckAccess方法的具体用法?C# Dispatcher.CheckAccess怎么用?C# Dispatcher.CheckAccess使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Windows.Threading.Dispatcher
的用法示例。
在下文中一共展示了Dispatcher.CheckAccess方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ScrollToEnd
public static void ScrollToEnd(Dispatcher dispatcher, ListBox listBox)
{
if (dispatcher.CheckAccess())
{
SelectLastEntry(listBox);
}
else
{
dispatcher.BeginInvoke(
DispatcherPriority.Send,
new VoidFunctionHandler(SelectLastEntry),
listBox);
}
}
示例2: AppShutdownDispatcher
public static void AppShutdownDispatcher(Dispatcher theMainDispatcher)
{
if (theMainDispatcher.CheckAccess())
{
theMainDispatcher.InvokeShutdown();
}
else
{
Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Send, (Action)(() =>
{
theMainDispatcher.InvokeShutdown();
}));
}
}
示例3: DispatcherConsumer
public DispatcherConsumer(Dispatcher dispatcher, TimeSpan minTimeSpan)
{
_dispatcher = dispatcher;
_minTimeSpan = HiResTimer.FromTimeSpan(minTimeSpan);
_timer = new Timer(state =>
{
_nextQuantumTime = HiResTimer.Now() + _minTimeSpan;
// prepare batch (generate lots of RunOnDispatcher notifications)
_runOnDispatcher = new List<Action>(); // TODO: race condition where this is null at X, need to prevent timers colliding?
Refresh();
// obtain dispatcher actions
List<Action> actions;
using (this.Lock())
{
actions = _runOnDispatcher;
_runOnDispatcher = null;
}
// execute batch on dispatcher
if (actions != null && actions.Count > 0) // X
{
if (_dispatcher.CheckAccess())
actions.ForEach();
else
_dispatcher.Invoke(new Action(() => actions.ForEach()), DispatcherPriority.DataBind);
}
});
_runOnRefresh.OnNotify =
() =>
{
// see if this is too short a time since last quantum?
var wait = Math.Max(0, _nextQuantumTime - HiResTimer.Now());
_timer.Change(HiResTimer.ToTimeSpan(wait), TimeSpan.FromMilliseconds(-1));
};
}
示例4: RunInDispatcher
public static void RunInDispatcher(Dispatcher dispatcher, DispatcherPriority priority, Action action)
{
if (action == null) { return; }
if (dispatcher.CheckAccess())
{
// we are already on thread associated with the dispatcher -> just call action
try
{
action();
}
catch (Exception ex)
{
//Log error here!
}
}
else
{
// we are on different thread, invoke action on dispatcher's thread
dispatcher.BeginInvoke(
priority,
(Action)(
() =>
{
try
{
action();
}
catch (Exception ex)
{
//Log error here!
}
})
);
}
}
示例5: ContactWatcherSingular
public ContactWatcherSingular(Dispatcher dispatcher, ContactLoader loader, string directory, ContactTypes type, ContactWatcherEventCallback callback)
{
Assert.IsNotNull(dispatcher);
// It's expected that this is created on the same thread as the manager,
// so don't need to go through the dispatcher for methods invoked in the constructor.
Assert.IsTrue(dispatcher.CheckAccess());
Assert.IsNotNull(loader);
Assert.IsFalse(string.IsNullOrEmpty(directory));
Assert.IsNotNull(callback);
Assert.IsTrue(Enum.IsDefined(typeof(ContactTypes), type));
Assert.AreNotEqual(ContactTypes.All, type);
Assert.AreNotEqual(ContactTypes.None, type);
_dispatcher = dispatcher;
_rootDirectory = directory;
_loader = loader;
_notify = callback;
_findExtension = "*" + Contact.GetExtensionsFromType(type);
// This is why creating this object is expensive:
// In order to be able to give accurate change notifications we need to know all the contacts that are present at the beginning.
_knownContacts = new Dictionary<string, ContactInfo>();
// _pushedFrames = 0;
_frame = new DispatcherFrame
{
Continue = false
};
// Create the timer, but only signal it if we're going to need to reprocess an update.
_timer = new Timer();
_timer.Tick += delegate
{
if (!_stopProcessing)
{
// Not invoked by the FileSystemWatcher, so don't push a frame here.
_dispatcher.Invoke(DispatcherPriority.Background, (ThreadStart)_ReprocessPendingUpdate);
}
};
_timer.Interval = TimeSpan.FromMilliseconds(_TimerMsDelay);
_timer.IsEnabled = false;
_PopulateKnownContacts(type);
_fileWatch = new FileSystemWatcher(_rootDirectory, _findExtension)
{
IncludeSubdirectories = true,
NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite | NotifyFilters.Attributes,
};
// There's some extra indirection required here because the manager requires thread affinity.
_fileWatch.Changed += FileSystemWatcher_OnChanged;
_fileWatch.Created += FileSystemWatcher_OnCreated;
_fileWatch.Deleted += FileSystemWatcher_OnDeleted;
_fileWatch.Renamed += FileSystemWatcher_OnRenamed;
_fileWatch.EnableRaisingEvents = true;
}
示例6: InvokeOnThread
static void InvokeOnThread(Dispatcher dispatcher, Action action, DispatcherPriority priority = DispatcherPriority.Normal, bool forceAsyncInvoke = true) {
if(dispatcher == null)
return;
if(!forceAsyncInvoke && dispatcher.CheckAccess())
action();
else
dispatcher.BeginInvoke(action, priority);
}
示例7: ParseIcons
private static void ParseIcons(
XmlReader reader, Dispatcher dispatcher,
IDictionary<string, ImageSource> icons)
{
while (reader.ReadToFollowing("UUID"))
{
var id = reader.ReadElementContentAsString();
if (reader.Name != "Data" &&
!reader.ReadToNextSibling("Data"))
{
continue;
}
var data = Convert.FromBase64String(
reader.ReadElementContentAsString());
BitmapImage image = null;
if (dispatcher.CheckAccess())
{
image = new BitmapImage();
image.SetSource(new MemoryStream(data));
}
else
{
var wait = new ManualResetEvent(false);
dispatcher.BeginInvoke(() =>
{
image = new BitmapImage();
image.SetSource(new MemoryStream(data));
wait.Set();
});
wait.WaitOne();
}
if (!icons.ContainsKey(id))
icons.Add(id, image);
}
}
示例8: FireScannerStateChanged
/// <summary>
/// The fire scanner state changed.
/// </summary>
/// <param name="dispatcher">
/// The dispatcher.
/// </param>
/// <param name="e">
/// The e.
/// </param>
private static void FireScannerStateChanged(Dispatcher dispatcher, NotifyScannerStateChangedEventArgs e)
{
NotifyScannerStateChangedEventHandler scannerStateChanged;
lock (SyncRoot)
{
if (currentScan != e.Id)
{
return;
}
scannerStateChanged = ScannerStateChanged;
}
if (scannerStateChanged != null)
{
if (dispatcher.CheckAccess())
{
scannerStateChanged(null, e);
}
else
{
dispatcher.Invoke(new Action<Dispatcher, NotifyScannerStateChangedEventArgs>(FireScannerStateChanged), DispatcherPriority.Send, dispatcher, e);
}
}
}
示例9: Generate3DModel
public void Generate3DModel(Dispatcher dispatcher)
{
if (!dispatcher.CheckAccess())
{
dispatcher.Invoke(() => Generate3DModel(dispatcher));
return ;
}
if (m_lights.Count == 0)
{
m_lights.Add(new DirectionalLight(Color.FromRgb(0xFF, 0xFF, 0xFF), new Vector3D(4, 6, -5)));
m_lights.Add(new DirectionalLight(Color.FromRgb(0xFF, 0xFF, 0xFF), new Vector3D(-4, -6, 5)));
m_lights.Add(new AmbientLight(Color.FromRgb(0x6F, 0x5F, 0x5F)));
}
m_model3DGroup = new Model3DGroup();
foreach (Light light in m_lights)
m_model3DGroup.Children.Add(light);
foreach (QbModelPart qbModelPart in m_parts)
{
qbModelPart.GenerateGeometry();
foreach (GeometryModel3D geometryModel3D in qbModelPart.Geometry)
{
m_model3DGroup.Children.Add(geometryModel3D);
}
}
//double maxX = m_parts.Max(n => n.Max.X);
//double maxY = m_parts.Max(n => n.Max.Y);
//double maxZ = m_parts.Max(n => n.Max.Z);
//double minX = m_parts.Min(n => n.Min.X);
//double minY = m_parts.Min(n => n.Min.Y);
//double minZ = m_parts.Min(n => n.Min.Z);
//BoundaryBox boundaryBox = new BoundaryBox(new Point3D(minX-0.5, minY-0.5, minZ-0.5), new Point3D(maxX + 0.5, maxY + 0.5, maxZ + 0.5), Colors.Purple);
//m_model3DGroup.Children.Add(boundaryBox.GeometryModel3D);
//double width = m_parts.Max(n => n.Width);
//double height = m_parts.Max(n => n.Height);
//double depth = m_parts.Max(n => n.Depth);
//boundaryBox = new BoundaryBox(new Point3D(-0.5, -0.5, -0.5), new Point3D(width - 0.5, depth - 0.5, height - 0.5), Colors.Goldenrod);
//m_model3DGroup.Children.Add(boundaryBox.GeometryModel3D);
double maxX = m_parts.Max(n => n.Max.X) + 1;
double maxY = m_parts.Max(n => n.Max.Y) + 1;
double minX = m_parts.Min(n => n.Min.X);
double minY = m_parts.Min(n => n.Min.Y);
m_ground = new Ground((int) minX, (int) maxX, (int) minY, (int) maxY, Scale);
foreach (GeometryModel3D geometryModel3D in m_ground.GeometryModel3D)
{
m_model3DGroup.Children.Add(geometryModel3D);
}
}
示例10: Do
/// <summary>
/// Fires off your delegate asyncronously, using the threadpool or a full managed thread if needed.
/// </summary>
/// <param name="d">A void delegate - can be cast to (Action) from an anonymous delgate.</param>
/// <param name="dr">A delegate with a return value of some sort - can be cast to (Func<object>) from an anonymous delgate with a return.</param>
/// <param name="state">A user object that can be tracked through the returned result</param>
/// <param name="getRetVal">If true, and the method/delgete returns something, it is included in the AsyncRes returned (after the method completes)</param>
/// <param name="tryThreadPool">True to use the TP, otherwise just go to a ful lthread - good for long running tasks.</param>
/// <param name="rMode">If true, will make sure no other instances are running your method.</param>
/// <returns>AsyncRes with all kind of goodies for waiting, result values, etc.</returns>
private static AsyncRes Do(Func<object> dr, Action d, bool getRetVal, object state, bool tryThreadPool, ReenteranceMode rMode, bool isAsync, Dispatcher dispatcher)
{
//get a generic MethodInfo for checks..
MethodInfo mi = ((dr != null) ? dr.Method : d.Method);
//make a unique key for output usage
string key = string.Format("{0}{1}{2}{3}", ((getRetVal) ? "<-" : ""), mi.DeclaringType, ((mi.IsStatic) ? ":" : "."), mi.Name);
//our custom return value, holds our delegate, state, key, etc.
AsyncRes res = new AsyncRes(state, ((dr != null) ? (Delegate)dr : (Delegate)d), key, rMode);
//Create a delegate wrapper for what we will actually invoke..
Action Action = (Action)delegate
{
if (!BeforeInvoke(res)) return; //checks for reentrance issues and sets us up
try
{
if (res.IsCompleted) return;
if (dr != null)
{
res.retVal = dr();//use this one if theres a return
}
else
{
d();//otherwise the simpler Action
}
}
catch (Exception ex)
{ //we never want a rogue exception on a random thread, it can't bubble up anywhere
System.Diagnostics.Debug.WriteLine("Async Exception:" + ex);
}
finally
{
FinishInvoke(res);//this will fire our callback if they used it, and clean up
}
};
if (dispatcher != null)
{
res.control = dispatcher;
res.result = AsyncAction.ControlInvoked;
if (!isAsync)
{
if (dispatcher.CheckAccess())
{
res.completedSynchronously = true;
Action();
}
else
{
dispatcher.BeginInvoke(Action);
}
}
else
{
dispatcher.BeginInvoke(Action);
}
return res;
} //don't catch these errors - if this fails, we shouldn't try a real thread or threadpool!
if (tryThreadPool)
{
//we are going to use the .NET threadpool
try
{
//this is what actually fires this task off..
bool result = ThreadPool.QueueUserWorkItem(delegate { Action(); });
if (result)
{
res.result = AsyncAction.ThreadPool;
//this means success in queueing and running the item
return res;
}
else
{
//according to docs, this "won't ever happen" - exception instead, but just for kicks.
System.Diagnostics.Debug.WriteLine("Failed to queue in threadpool. Method: " + key);
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Failed to queue in threadpool: " + ex.Message, "Method: " + key);
}
}
//if we got this far, then something up there failed, or they wanted a dedicated thread
Thread t = new Thread((ThreadStart)delegate { Action(); }) { IsBackground = true, Name = ("Async_" + key) };
res.result = AsyncAction.Thread;
t.Start();
return res;
//.........这里部分代码省略.........
示例11: WPFBlitPresenter
public WPFBlitPresenter(DirectCanvasFactory directCanvas, int width, int height, Dispatcher dispatcher)
: base(directCanvas)
{
m_width = width;
m_height = height;
/* Check and see if we are on the UI thread as we may want to support
* multi-threaded scenarios */
if (!dispatcher.CheckAccess())
{
dispatcher.Invoke((Action)delegate
{
m_d3dImage = new D3DImage();
});
}
else
{
m_d3dImage = new D3DImage();
}
/* Initialize our special layers */
CreateLayer(m_width, m_height);
}
示例12: ExecuteOnUIThread
public static void ExecuteOnUIThread(Action action, Dispatcher dispatcher)
{
if (dispatcher.CheckAccess())
action();
else
dispatcher.BeginInvoke(action);
}
示例13: DispatchWhenRequired
private void DispatchWhenRequired( Dispatcher d, Action a )
{
if( d.CheckAccess() ) a();
else d.Invoke( a );
}