Reputation: 82507
I have the following code:
var queue = printer.PrintQueue;
var canPrint = ! Dispatcher.CurrentDispatcher.Invoke(()
=> queue.IsPaperJammed || queue.IsOutOfPaper ||
queue.IsInError || queue.HasPaperProblem);
It is throwing the following error:
The calling thread cannot access this object because a different thread owns it
I have tried this on UI thread (using the dispatcher as shown above) and I have tried it on the current thread (without the dispatcher).
Is there a way to ask a object which thread owns it?
Upvotes: 3
Views: 879
Reputation: 19511
just crazy as it is, the following code did not work, and it still throws the exception
dlg.PrintTicket.PageMediaSize = new PageMediaSize(302.36220472, int.MaxValue);
dlg.PrintTicket.PageOrientation = PageOrientation.Portrait;
but this code worked
dlg.PrintTicket = new PrintTicket()
{
PageMediaSize = new PageMediaSize(273, int.MaxValue),
PageOrientation = PageOrientation.Portrait,
};
of course the both code must be in Application.Current.Dispatcher.Invoke(() => {})
but still the first will throw the exception and the second will solve the problem
Upvotes: 0
Reputation: 374
There is a way to determine if the CURRENT thread owns a control:
Use control.Dispatcher.CheckAccess()
to check whether the current thread owns the control. If it does not own it then Invoke
an Action
using dispatcher.
Upvotes: 0
Reputation: 89325
Have you tried without CurrentDispatcher
? :
var canPrint = ! Application.Current.Dispatcher.Invoke(()
=> queue.IsPaperJammed || queue.IsOutOfPaper ||
queue.IsInError || queue.HasPaperProblem);
CurrentDispatcher.Invoke()
will invoke your code from the thread currently executing, it is non-UI thread assuming that snippet in this question is run from non-UI thread.
References :
Upvotes: 4