WPF: Storyboard loop object owned by another thread - wpf

Hi all my simple code looks like this
private void flipForeverever(object sender, EventArgs args)
{
moveYs = new DoubleAnimation();
m2oveYs = new DoubleAnimation();
try
{
sf.Remove(this);
sf.Children.Clear();
}
catch (Exception e)
{
}
if (firstPanelAngle == 360)
{
moveYs.To = 180;
moveYs.From = 0;
}
else
{
moveYs.To = 360;
moveYs.From = 180;
}
if (secondPanelAngle == 360)
{
m2oveYs.To = 180;
m2oveYs.From = 0;
}
else
{
m2oveYs.To = 360;
m2oveYs.From = 180;
}
sf = (Storyboard)FindResource("Storyboard1");
Storyboard.SetTargetName(moveYs, "rotatePanel");
Storyboard.SetTargetProperty(moveYs, new thisPropertyPath(AxisAngleRotation3D.AngleProperty));
Storyboard.SetTargetName(m2oveYs, "rotateSecond");
Storyboard.SetTargetProperty(m2oveYs, new PropertyPath(AxisAngleRotation3D.AngleProperty));
sf.Children.Add(moveYs);
sf.Children.Add(m2oveYs);
// sf.RepeatBehavior = RepeatBehavior.Forever;
if (flipForever)
{
sf.Completed += new EventHandler(delaythespin);
sf.Begin(this);
}
}
private void delaythespin(object sender, EventArgs args)
{
sf.Stop(this);
System.Timers.Timer timer = new System.Timers.Timer(500);
timer.Elapsed += new System.Timers.ElapsedEventHandler(flipForeverever);
timer.Enabled = true;
firstPanelAngle = rotatePanel.Angle;
secondPanelAngle = rotateSecond.Angle;
timer.Start();
}
So basically i call flipForeverever through a click call and it is supposed to loop forever until i set flipforever to false... But then it is giving me this error...
The calling thread cannot access this object because a different thread owns it.
Any help will really be appreciated

It sounds like you might be having thread affinity problems. Have you tried using a DispatcherTimer instead of a System.Timers.Timer?
private DispatcherTimer _timer;
private void GoButton_Click(object sender, RoutedEventArgs e)
{
_timer = new DispatcherTimer(); // create timer
_timer.Interval = new TimeSpan(0, 0, 1); // tick every 1s
_timer.Tick += new EventHandler(_timer_Tick); // method to call
_timer.Start(); // start timer
}
void _timer_Tick(object sender, EventArgs e)
{
// we should be on the correct thread now
GoButton.Background = Brushes.Aqua;
}
Or, if you need to use System.Timers.Timer, use Invoke or BeginInvoke to get on the correct thread after the timer fires?
private System.Timers.Timer _timer;
private void GoButton_Click(object sender, RoutedEventArgs e)
{
_timer = new System.Timers.Timer(1000);
_timer.Elapsed += new System.Timers.ElapsedEventHandler(_timer_Elapsed);
_timer.Start();
}
void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
// use Dispatcher.Invoke on the UI object that you want to modify
// to get on the correct thread for that UI object
GoButton.Dispatcher.Invoke((ThreadStart)(() =>
{
GoButton.Background = Brushes.Aqua;
}));
}

Related

How can I update my WinForm label on timer?

I can't update my WinForm label properties.
Details: I am trying to check my database and get some values posted, but I can't even update a mere label it seems. I'm using SharpDevelop.
The code:
//this is my form
public partial class MainForm : Form
{
//Declaring timer
public static System.Timers.Timer aTimer = new System.Timers.Timer();
public MainForm()
{
InitializeComponent();
//Timer
aTimer.Elapsed +=new ElapsedEventHandler(OnTimedEvent);
aTimer.Interval = 2000; //milisecunde
aTimer.Enabled = true;
label1.Text="some_text";
}
private static void OnTimedEvent(object source, ElapsedEventArgs e) {Check();}
public static void Check()
{
//Database checks here..
try{label1.Text="new_text";}catch(Exception e) {MessageBox.Show(e.ToString());}
MessageBox.Show("BAAAA");
}
void Button1Click(object sender, EventArgs e)
{
label1.Text = "mergeeeeee?!";
}
}
EDIT: I've removed all static modifiers. Also updated the post with the new code (try catch is added and the messagebox after it + a button that changes the label).
The try catches the following error:
. Really could use some help, been researching answers for more than 6 hours.
Try this (use a System.Windows.Forms.Timer instead of System.Timers.Timer):
//Declaring timer
public System.Windows.Forms.Timer aTimer = new System.Windows.Forms.Timer();
public Form1()
{
InitializeComponent();
//Timer
aTimer.Tick += aTimer_Tick;
aTimer.Interval = 2000; //milisecunde
aTimer.Enabled = true;
label1.Text = "some_text";
}
void aTimer_Tick(object sender, EventArgs e)
{
Check();
}
public void Check()
{
try
{
//Database checks here..
label1.Text = string.Format("new_text {0}", DateTime.Now.ToLongTimeString());
}
catch (Exception ex)
{
throw ex;
}
MessageBox.Show("BAAAA");
}
The Elapsed event of the System.Timers.Timer is fired on a non-UI thread (change your original code to not swallow exceptions and you should see the cross-thread exception).
I used the following code for my project and it worked.
It has a button to activate the timer and the timer raises an event when 500 milliseconds passed.
private void ActiveTimer_Click(object sender, EventArgs e)
{
EnableTimer();
}
private void EnableTimer()
{
System.Timers.Timer raiseTimer = new System.Timers.Timer();
raiseTimer.Interval = 500;
raiseTimer.Elapsed += RaiseTimerEvent;
raiseTimer.AutoReset = true;
raiseTimer.Enabled = true;
}
private void RaiseTimerEvent(object sender, System.Timers.ElapsedEventArgs e)
{
this.Invoke(new Action(() =>
{
label1.Text += "500 ms passed\n";
}));
}

How to detect a Touch Press and Hold gesture in a WPF application?

It is possible to detect a touch press and hold gesture with the MouseRightButtonDown event. Unfortunately it fires not until I release my finger from the screen. This is to late!
Does anyone have ideas? Thanks in advance.
It is possible to do that in an awaitable fashion. Create a timer with specific interval. Start it when user tapped and return the method when timer elapsed. If user release the hand, return the method with false flag.
public static Task<bool> TouchHold(this FrameworkElement element, TimeSpan duration)
{
DispatcherTimer timer = new DispatcherTimer();
TaskCompletionSource<bool> task = new TaskCompletionSource<bool>();
timer.Interval = duration;
MouseButtonEventHandler touchUpHandler = delegate
{
timer.Stop();
if (task.Task.Status == TaskStatus.Running)
{
task.SetResult(false);
}
};
element.PreviewMouseUp += touchUpHandler;
timer.Tick += delegate
{
element.PreviewMouseUp -= touchUpHandler;
timer.Stop();
task.SetResult(true);
};
timer.Start();
return task.Task;
}
For more information, read this post.
Great piece of code. I add just an example usage for completeness:
private async void btn_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
if (await TouchHold(btn, TimeSpan.FromSeconds(2)))
{
// todo: long press code goes here
}
}
And from XAML:
<Button Name="btn" PreviewMouseDown="btn_PreviewMouseDown">Press long</Button>
Use the Hold gesture provided by Blake.NUI toolkit
Either a button or label or image, we can use the MouseDown and MouseUp for starting the delay and Stopping the delay.
For MouseDown,
// Declaration of timer and timercount
int timerCount = 0;
DispatcherTimer dt = new DispatcherTimer();
public myConstructor()
{
dt.Interval = new TimeSpan(0, 0, 1);
}
// Mouse Down Event
private void EnterHoldState(object sender, TouchEventArgs e)
{
timerStarted();
}
//Mouse Up event
private void ExitHoldState(object sender, RoutedEventArgs e)
{
timerStopped();
}
// Stops the timer and resets the timer count to 0
private void timerStopped()
{
dt.Stop();
timerCount = 0;
}
// Starts the timer and sets delayCounter function for counting the delay seconds and acts on it
private void timerStarted()
{
dt.Tick += delayCounter;
dt.Start();
}
//Once delay timer reaches 2 seconds, the button navigates to nextpage.
private void delayCounter(object sender, EventArgs e)
{
timerCount++;
if (timerCount == 2)
{
this.NavigationService.Navigate(new nextPage());
}
}
I recently had to implement a Button where I needed to it to trigger after being pressed for five seconds.
To do this I created an attached behavior. I have the five seconds backed into the behavior as I did not need this configurable but easily done with a Dependency Property and it is hooked up to be used with a Command in an MVVM way but it could easily be changed to trigger Click.
<Button Command="{Binding Path=ButtonCommand}">
<i:Interaction.Behaviors>
<behaviors:PressAndHoldBehavior />
</i:Interaction.Behaviors>
</Button>
public sealed class PressAndHoldBehavior : Behavior<Button>
{
private DispatcherTimer dispatcherTimer;
protected override void OnAttached()
{
dispatcherTimer = new DispatcherTimer {Interval = TimeSpan.FromSeconds(5)};
dispatcherTimer.Tick += OnDispatcherTimerTick;
AssociatedObject.PreviewMouseLeftButtonDown += AssociatedObjectPreviewMouseLeftButtonDown;
AssociatedObject.PreviewMouseLeftButtonUp += AssociatedObjectPreviewMouseLeftButtonUp;
}
protected override void OnDetaching()
{
dispatcherTimer.Stop();
dispatcherTimer.Tick -= OnDispatcherTimerTick;
dispatcherTimer = null;
AssociatedObject.PreviewMouseLeftButtonDown -= AssociatedObjectPreviewMouseLeftButtonDown;
AssociatedObject.PreviewMouseLeftButtonUp -= AssociatedObjectPreviewMouseLeftButtonUp;
}
private void AssociatedObjectPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
dispatcherTimer.Start();
e.Handled = true;
}
private void AssociatedObjectPreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
dispatcherTimer.Stop();
e.Handled = true;
}
private void OnDispatcherTimerTick(object sender, EventArgs e)
{
AssociatedObject.Command.Execute(null);
}
}

how to close all the open form in WPF

In my Application I have two buttons "open" and "close".
When I click open button window will be opened, when I click close button window will be closed.
When I click open button 3 times, 3 windows will be opened. I want to close all window when I click close button.
Here is my code [Please don't try to Change the Thread because that is my requirement in my Application]
public partial class MainWindow : Window
{
Window ProgressWindow;
Thread ProgressThread;
public MainWindow()
{
InitializeComponent();
}
private void Open_Click(object sender, RoutedEventArgs e)
{
ProgressThread = new Thread(() =>
{
ProgressWindow = new Window();
ProgressWindow.Margin = new Thickness(0, 0, 50, 0);
ProgressWindow.WindowState = WindowState.Normal;
ProgressWindow.WindowStartupLocation = WindowStartupLocation.CenterScreen;
ProgressWindow.Height = 180;
ProgressWindow.Width = 180;
ProgressWindow.Content = "Hello WPF";
ProgressWindow.ShowInTaskbar = false;
ProgressWindow.Show();
ProgressWindow.Closed += (sender2, e2) =>
ProgressWindow.Dispatcher.InvokeShutdown();
System.Windows.Threading.Dispatcher.Run();
});
ProgressThread.SetApartmentState(ApartmentState.STA);
ProgressThread.Start();
}
private void Close_Click(object sender, RoutedEventArgs e)
{
if (ProgressThread.IsAlive == true)
{
ProgressThread.Abort();
}
}
}
I would recommend to store references to created windows, your code can look like this:
Stack<Window> ProgressWindow=new Stack<Window>();
Thread ProgressThread;
private void Open_Click(object sender, RoutedEventArgs e)
{
ProgressThread = new Thread(() =>
{
var window = new Window();
window.Margin = new Thickness(0, 0, 50, 0);
window.WindowState = WindowState.Normal;
window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
window.Height = 180;
window.Width = 180;
window.Content = "Hello WPF";
window.ShowInTaskbar = false;
window.Show();
window.Closed += (sender2, e2) =>
window.Dispatcher.InvokeShutdown();
ProgressWindow.Push(window);
System.Windows.Threading.Dispatcher.Run();
});
ProgressThread.SetApartmentState(ApartmentState.STA);
ProgressThread.Start();
}
private void Close_Click(object sender, RoutedEventArgs e)
{
while (ProgressWindow.Count > 0)
{
ProgressWindow.Pop().Close();
}
}
thread aborting is not recommended if it is "normal" workflow of your application, i.e. window wasn't closed because of some critical error
I wouldn't recommend what you are doing and actually I don't really know if it works like this, but since you stated that it's your (strange) requirement to use threads like this, I will only comment on the actual problem:
You should save the threads in a List and then close all the threads from this list.
Edit:
public partial class MainWindow : Window
{
Window ProgressWindow;
List<Thread> ProgressThreads = new List<Thread>();
public MainWindow()
{
InitializeComponent();
}
private void Open_Click(object sender, RoutedEventArgs e)
{
ProgressThreads.Add(new Thread(() =>
{
ProgressWindow = new Window();
ProgressWindow.Margin = new Thickness(0, 0, 50, 0);
ProgressWindow.WindowState = WindowState.Normal;
ProgressWindow.WindowStartupLocation = WindowStartupLocation.CenterScreen;
ProgressWindow.Height = 180;
ProgressWindow.Width = 180;
ProgressWindow.Content = "Hello WPF";
ProgressWindow.ShowInTaskbar = false;
ProgressWindow.Show();
ProgressWindow.Closed += (sender2, e2) =>
ProgressWindow.Dispatcher.InvokeShutdown();
System.Windows.Threading.Dispatcher.Run();
}));
ProgressThread.SetApartmentState(ApartmentState.STA);
ProgressThread.Start();
}
private void Close_Click(object sender, RoutedEventArgs e)
{
foreach(var ProgressThread in ProgressThreads)
{
if (ProgressThread.IsAlive == true)
{
ProgressThread.Abort();
}
}
}
}
You will need to keep a record of all threads you have opened when you click "Open". Then in your "Close" method loop over that list closing each one.
Member variable:
List<Thread> allThreads = new List<Thread>();
Then in your open handler add:
allThreads.Add(ProgressThread);
Then your close handler becomes:
foreach (Thread thread in allThreads)
{
if (thread.IsAlive)
{
thread.Abort();
}
}
That what you are trying is unorthodox should go without saying.

WPF & Multi-threading questions

I'm working on building a multi-threaded UI. I would like long processes to be handled by the BackgroundWorker class, and have a small timer on the UI to keep track of how long the process is taking. It's my first time building such a UI, so I'm reading up on related resources on the web. My test code is thus:
private BackgroundWorker worker;
private Stopwatch swatch = new Stopwatch();
private delegate void simpleDelegate();
System.Timers.Timer timer = new System.Timers.Timer(1000);
string lblHelpPrevText = "";
private void btnStart_Click(object sender, RoutedEventArgs e)
{
try
{
worker = new BackgroundWorker(); //Create new background worker thread
worker.DoWork += new DoWorkEventHandler(BG_test1);
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(BG_test1end);
worker.RunWorkerAsync();
simpleDelegate del = new simpleDelegate(clockTicker);
AsyncCallback callBack = new AsyncCallback(clockEnd);
IAsyncResult ar = del.BeginInvoke(callBack, null);
lblHelpText.Text = "Processing...";
}
finally
{
worker.Dispose(); //clear resources
}
}
private void clockTicker()
{
//Grab Text
simpleDelegate delLblHelpText = delegate()
{ lblHelpPrevText = this.lblHelpText.Text; };
this.Dispatcher.BeginInvoke(DispatcherPriority.Send, delLblHelpText);
//Start clock
timer.Elapsed += new ElapsedEventHandler(clockTick);
timer.Enabled = true;
swatch.Start();
}
private void clockTick(object sender, ElapsedEventArgs e)
{
simpleDelegate delUpdateHelpTxt = delegate()
{ this.lblHelpText.Text = String.Format("({0:00}:{1:00}) {2}", swatch.Elapsed.Minutes, swatch.Elapsed.Seconds, lblHelpPrevText); };
this.Dispatcher.BeginInvoke(DispatcherPriority.Send, delUpdateHelpTxt);
}
private void BG_test1(object sender, DoWorkEventArgs e)
{
//this.lblHelpText.Text = "Processing for 10 seconds...";
Thread.Sleep(15000);
}
private void BG_test1end(object sender, RunWorkerCompletedEventArgs e)
{
this.lblHelpText.Text = "Process done.";
this.timer.Enabled = false;
this.swatch.Stop();
this.swatch.Reset();
}
static void clockEnd(IAsyncResult ar)
{
simpleDelegate X = (simpleDelegate)((AsyncResult)ar).AsyncDelegate;
X.EndInvoke(ar);
}
The idea is when the button is clicked, we take the status text from a Label (e.g. "Processing...") then append the time onto it every second. I could not access the UI elements from the Timer class as it's on a different thread, so I had to use delegates to get and set the text.
It works, but is there a better way to handle this? The code seems much for such a basic operation. I'm also not fully understanding the EndInvoke bit at the bottom. I obtained the snippet of code from this thread Should One Always Call EndInvoke a Delegate inside AsyncCallback?
I understand the idea of EndInvoke is to receive the result of BeginInvoke. But is this the correct way to use it in this situation? I'm simply worried about any resource leaks but when debugging the callback appears to execute before my timer starts working.
Don't use a separate timer to read the progress of your BackgroundWorker and update the UI. Instead, make the BackgroundWorker itself "publish" its progress to the UI directly or indirectly.
This can be done pretty much anyway you want to, but there's a built-in provision exactly for this case: the BackgroundWorker.ProgressChanged event.
private void BG_test1(object sender, DoWorkEventArgs e)
{
for(var i = 0; i < 15; ++i) {
Thread.Sleep(1000);
// you will need to get a ref to `worker`
// simplest would be to make it a field in your class
worker.ReportProgress(100 / 15 * (i + 1));
}
}
This way you can simply attach your own handler to ProgressChanged and update the UI using BeginInvoke from there. The timer and everything related to it can (and should) go.
You can use timer to update UI. It is normal practice. Just instead of System.Timer.Timer I suggest use System.Windows.Threading.DispatcherTimer. The DispatcherTimer runs on the same thread as the Dispatcher. Also, instead of BackgroundWorker you can use ThreadPool.
Here is my sample:
object syncObj = new object();
Stopwatch swatch = new Stopwatch();
DispatcherTimer updateTimer; // Assume timer was initialized in constructor.
void btnStart_Click(object sender, RoutedEventArgs e) {
lock (syncObj) {
ThreadPool.QueueUserWorkItem(MyAsyncRoutine);
swatch.Start();
updateTimer.Start();
}
}
void updateTimer_Tick(object sender, EventArgs e) {
// We can access UI elements from this place.
lblHelpText.Text = String.Format("({0:00}:{1:00}) Processing...", swatch.Elapsed.Minutes, swatch.Elapsed.Seconds);
}
void MyAsyncRoutine(object state) {
Thread.Sleep(5000);
lock (syncObj)
Dispatcher.Invoke(new Action(() => {
swatch.Stop();
updateTimer.Stop();
lblHelpText.Text = "Process done.";
}), null);
}
private void button1_Click(object sender, EventArgs e)
{
string strFullFilePath = #"D:\Print.pdf";
ProcessStartInfo ps = new ProcessStartInfo();
ps.UseShellExecute = true;
ps.Verb = "print";
ps.CreateNoWindow = true;
ps.WindowStyle = ProcessWindowStyle.Hidden;
ps.FileName = strFullFilePath;
Process.Start(ps);
Process proc = Process.Start(ps);
KillthisProcess("AcroRd32");
}
public void KillthisProcess(string name)
{
foreach (Process prntProcess in Process.GetProcesses())
{
if (prntProcess.ProcessName.StartsWith(name))
{
prntProcess.WaitForExit(10000);
prntProcess.Kill();
}
}
}

Cannot Get Threading right on wpf UI

I am building a proof of concept application before it gets rollout to the real one.
Scenario
I should be able to stop processing in the middle of it.
Toolbar 2 buttons "Start" & "Stop"
User press start and it process a long running task.
User decides out of the blue to stop the task.
I cannot seem to get threading right!! I cannot press stop as it's waiting for the long running task as if the long running task is actually running on UI thread and not as intented on background thread.
What Am I doing wrong can you spot it? Thanks for your help
public partial class TestView : UserControl
{
private readonly BackgroundWorker _worker;
public TestView
{
InitializeComponent();
_worker = new BackgroundWorker();
_worker.RunWorkerCompleted += RunWorkerCompleted;
_worker.DoWork+=DoWork;
_worker.WorkerReportsProgress = true;
_worker.ProgressChanged+=_worker_ProgressChanged;
_worker.WorkerSupportsCancellation = true;
}
static void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
MessageBox.Show("The task has been cancelled");
}
else if (e.Error != null)
{
MessageBox.Show("Error. Details: " + e.Error);
}
else
{
MessageBox.Show("The task has been completed. Results: " + e.Result);
}
}
private delegate void SimpleDelegate();
void DoWork(object sender, DoWorkEventArgs e)
{
for (var i = 0; i < 1000000; i++)
{
_worker.ReportProgress(i, DateTime.Now);
// SimpleDelegate simpleDelegate = () => txtResult.AppendText("Test" + System.Environment.NewLine);
//Dispatcher.BeginInvoke(DispatcherPriority.Normal, simpleDelegate);
}
MessageBox.Show("I have done it all");
}
private void _worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
DateTime time = Convert.ToDateTime(e.UserState);
txtResult.AppendText(time.ToLongTimeString());
txtResult.AppendText(Environment.NewLine);
}
private void BtnStart_Click(object sender, RoutedEventArgs e)
{
_worker.RunWorkerAsync();
}
private void BtnStop_Click(object sender, RoutedEventArgs e)
{
_worker.CancelAsync();
MessageBox.Show("Process has been stopped!");
}
}
You run a very tight loop inside of DoWork and continuously push Invoked ProgressUpdates to the Main Thread. That will make it sluggish.
But the real problem is that DoWork has to cooperate in Cancellation:
void DoWork(object sender, DoWorkEventArgs e)
{
for (var i = 0; i < 1000000; i++)
{
if (_worker.CancelationPending)
{
e.Cancel = true;
break; // or: return to skip the messagebox
}
_worker.ReportProgress(i, DateTime.Now);
}
MessageBox.Show("I have done it all"); // remove or make depend on Cancelled
}

Resources