.NET 5.0 - Stop immediately a running thread in WPF application - wpf

I'm developing a WPF application for real-time data gathering from a remote client. Data acquisition is managed by a different thread (different from the one used to run the main application). When the users press the connection button, the data acquisition thread is launched and, simmetrically, when the disconnection button is pressed the thread should stop. Data reading stops only when the user decides it.
I use the following code:
private void ConnectButton_Click(object sender, RoutedEventArgs e)
{
connectionThread = new Thread(new ThreadStart(myThreadStartFunc));
connectionThread.Start();
}
private void myThreadStartFunc()
{
TcpConnect();
ReadData();
}
private void TcpConnect()
{
mySocket = new Socket(...);
mySocket.Connect(ipEndPoint);
}
private void ReadData()
{
while(mySocket.Connected)
{
Thread.Sleep(300);
mySocket.Receive(data, ...);
}
}
private void DisconnectButton_Click(object sender, RoutedEventArgs e)
{
StopThread(connectionThread);
}
private void StopThread(Thread thread)
{
}
What should be the body of the StopThread method? Currently I'm using thread.Interrupt() in a try and catch structure in thte StopThread method. It generates an exception in the while loop of the data reading method, at line Thread.Sleep(300): System.Threading.ThreadInterrupted
Exception: Thread was interrupted from a waiting state.
I would like to use the thread.Abort() method, but it is obsolete (https://learn.microsoft.com/en-us/dotnet/core/compatibility/core-libraries/5.0/thread-abort-obsolete). Any suggestion? Thank you in advance.

Related

Using System.Threading.Timer in Compact Framework

I am using a System.Threading.Timer in a CF project (Windows Embedded CE 6.0), VS2005 C#, .NET 2.0.
This timer is desired because there is no possibility of reentrancy when used like this:
private System.Threading.Timer mainTimer;
private void MainForm_Load(object sender, EventArgs e)
{
// other initializations
mainTimer = new System.Threading.Timer(new TimerCallback(timerMain_Tick),
null, 100, Timeout.Infinite);
}
Which is to say, dueTime parameter is used but period is not. As long as period is Timeout.Infinite, the timer will fire once only. The timer is made thread-safe by checking for the form's InvokeRequired property. Note the check for null. It relates to my question, which I am getting to quickly.
private void timerMain_Tick(object stateInfo)
{
if (mainTimer != null)
{
if (this.InvokeRequired)
{
this.Invoke((ThreadStart)delegate
{
TimerProcess();
});
}
else
{
TimerProcess();
}
}
}
The timer must restart itself before it exits.
private void TimerProcess()
{
try
{
// do work here
}
finally
{
// retrigger
mainTimer.Change(mainTimerInterval, Timeout.Infinite);
}
}
The problem I am having is gracefully stopping this darn thing.
private void MainForm_Closing(object sender, CancelEventArgs e)
{
// shut down timer
mainTimer.Change(Timeout.Infinite, Timeout.Infinite);
mainTimer.Dispose();
mainTimer = null;
}
About 3 times in 10, the timer fires anyway, and I get an Object Disposed error. The timer code is trying to invoke the timer method AFTER the check for null.
I suspect that the timer fires, and its thread is suspended while the form is closing. I tried a state machine enumeration:
Normal state Running
Form_Closing sets Stopping state and waits in a Thread.Sleep() loop for Stopped state
Timer sees Stopping and sets Stopped state (rather than retriggering itself)
Problem I had with this is that the timer thread would not preempt the form closing method, so get stuck in endless loop.
How to fix this problem? Note that in CF, there is no Dispose(WaitHandle) method.
Interesting problem. There do not seem to be many options with the Timer in the Compact Framework.
I'm not sure how your specific code works, so adding a single static Boolean value may or may not fix your issues.
Here is how I changed your code to accept a timerOK value. If this does not solve your problem, it could give you ideas on how to approach this.
private static bool timerOK;
private static long mainTimerInterval = 200;
private System.Threading.Timer mainTimer;
private void MainForm_Load(object sender, EventArgs e) {
timerOK = true;
mainTimer = new System.Threading.Timer(new TimerCallback(timerMain_Tick), null, 100, Timeout.Infinite);
}
private void MainForm_Closing(object sender, CancelEventArgs e) {
timerOK = false;
mainTimer.Change(Timeout.Infinite, Timeout.Infinite);
mainTimer.Dispose();
mainTimer = null;
}
private void timerMain_Tick(object stateInfo) {
if (timerOK && (mainTimer != null)) {
if (this.InvokeRequired) {
this.Invoke((ThreadStart)delegate {
TimerProcess();
});
} else {
TimerProcess();
}
}
}
private void TimerProcess() {
if (!timerOK) return;
try {
// do work here
} finally {
// retrigger
mainTimer.Change(mainTimerInterval, Timeout.Infinite);
}
}
I'm using MVP so my layout is a little different, but essentially I had the same two problems to fix:
Stop the timer firing after targets in the process method are disposed
Stop the timer firing DURING disposal
First one is easily fixed as pwrgreg007 shows above, just shutdown and null the timer sometime in your 'closing' process (before the form targets are disposed) and then do a null check at the start of your timer processing event.
Second issue is a bit trickier, even if the timer (and your form) are running at the start of your processing loop, nothing stops it getting shutdown mid way through the process as it is running on a different thread. To prevent this I created a lock to be used both during the timer execution AND the timer shutdown.
//simplified presenter
public class Presenter
{
private const int REFRESH_TIME_MILLISECONDS = 5000;
private view _view;
private Timer _timer;
private object _timerLock = new object();
//CTOR
public Presenter()
{
_view = new View();
Startup();
}
//spin up presenter
public void Startup(){
//bind view shutdown event
_view.ViewClosing += Shutdown;
//start timer
_timer = new Timer(DoTimerStuff, null, REFRESH_TIME_MILLISECONDS, Timeout.Infinite);
}
//spin down presenter
public void Shutdown()
{
//wait for any DoTimerStuff locks to expire
lock (_timerLock)
{
//stop the timer
_timer.Change(Timeout.Infinite, Timeout.Infinite);
_timer.Dispose();
_timer = null;
}
//close the view
_view.Shutdown();
}
//timer tick
private void DoTimerStuff(object state)
{
//grab a lock so we can ensure the timer doesn't get shutdown mid way through
lock (_timerLock)
{
//make sure the timer isn't shutdown (from form closing)
if (_timer == null) return;
//do your stuff here
_view.SomeInvokedCheckedProperty = "SomeValue";
//etc...
//schedule next timer execute (runs every runtime + refresh time)
_timer.Change(REFRESH_TIME_MILLISECONDS, Timeout.Infinite);
}
}
}
//simplified view
public class View : Form
{
//view properties (make sure they are invoke checked)
public SomeInvokedCheckedProperty {get;set;}
//Bound to ViewClosing
private void View_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
//stop the view closing itself
e.Cancel = true;
//tell the presenter to handle closing instead
if (ViewClosing != null) ViewClosing.Invoke();
}
}
That way..
The timer will wait to shutdown (holding up your form close) if DoTimerStuff() has the lock and is currently running
Conversely, DoTimerStuff() will wait if the timer shutdown has the lock and when it gets to continue it will correctly see the timer is shutdown (and do nothing).

wpf working state

I have a grid in my application. After user selects some files in ofdialog application processes some calculations. While app is making calculations it looks like it is not responding. How to display some picture and make main window in black&white while calculating? Maybe make some dp in MainWindow a la "IsBusy" and bind a popup with picture to it?
How you implement this logic in yours apps?
One easy way is to use the busy indicator from Extended WPF Toolkit:
Dowload the binaries and add project reference to WPFToolkit.Extended.dll.
Next add following namespace in your 'main window':
xmlns:ext="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit.Extended"
Then add the busy indicator in the view (place it so that when shown, it will occupy the whole screen) Here my main window has two rows and I want the control to span on both rows. The control's IsBusy property is bound to a bool property in the view's data context.
<ext:BusyIndicator Grid.RowSpan="2" x:Name="busyIndicator" IsBusy="{Binding IsBusy}" />
The long lasting calculation should be processed in another thread so that it won't block the user interface. For threading you can use BackgroundWorker class.
You should have the long running tasks in a seperate thread to avoid UI blocking.
Here's one way you could achieve that:
Define background thread as below:
//Delegate that you could pass into the worker thread
public delegate void ProgressMonitor(string s);
//Call this to start background work
void StartLongRunningWork(ProgressMonitor mon)
{
using (BackgroundWorker bgw = new BackgroundWorker())
{
bgw.DoWork += WorkerThread;
bgw.RunWorkerCompleted += WorkerThreadCompleted;
bgw.RunWorkerAsync(mon);
}
}
void WorkerThread(object sender, DoWorkEventArgs e)
{
ProgressMonitor pm = (ProgressMonitor)e.Argument;
WorkerActual(pm, <any other parameters>);
}
void WorkerActual(ProgressMonitor pm,<any other parameters>)
{
...
pm("Doing x");
Do long running task
pm("Doing y");
...
}
//This function is called in case of Exception, Cancellation or successful completion
//of the background worker. Handle each event appropriately
void WorkerThreadCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
//Long running task threw an exception
}
else
if (e.Cancelled)
{
//Long running task was cancelled
}
else
{
//Long running task was successfuly completed
}
}
And Call it as below:
private void UpDateProgressLabel(string s)
{
this.Dispatcher.BeginInvoke((Action)delegate
{
NotificationLabel.Content = s;
});
}
private void Button_Click(object sender, RoutedEventArgs e)
{
StartLongRunningWork(UpDateProgressLabel);
}

Winforms StatusStrip - why are there periods where it is blank when I'm updating it?

BACKGROUND: I have a WindowForms v3.5 application with a StatusStrip set to be used as a TooStripStatusLabel. I'm issues quite a lot of updates to it during a task that is running, however there are noticable periods where it is BLANK. There are no points when I am writing a blank to the status strip label either.
QUESTION: Any ideas why I would be seeing period where the status strip label is blank, when I don't expect it to be?
How I update it:
private void UpdateStatusStrip(string text)
{
toolStripStatusLabel1.Text = text;
toolStripStatusLabel1.Invalidate();
this.Update();
}
PS. Calling Application.DoEvents() after the this.Update() does not seem to help. I actually am calling this via the backgroundworker control, so:
(a) I start up the background worker:
private void Sync_Button_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
DisableUpdateButtons();
}
(b) the background worker calls updates:
private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
backgroundWorker1.ReportProgress(1, "Example string");
MainForm.MyC.SyncFiles(sender);
}
(c) The MyC business class uses it too, e.g.
public void SyncFiles(object sender)
{
BackgroundWorker bgw = (System.ComponentModel.BackgroundWorker) sender;
bgw.ReportProgress(1, "Starting sync...");
.
.
.
}
(d) This event picks it up:
private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
UpdateStatusStrip((string)e.UserState);
}
(e) And again the update status strip
private void UpdateStatusStrip(string text)
{
toolStripStatusLabel1.Text = text;
toolStripStatusLabel1.Invalidate();
this.Update();
}
Does this help?
The reason is possibly in the caller of this function. If you call it from another thread, use Control.BeginInvoke instead of direct call. If you call it from the main application thread during long processing, try Application.DoEvents after UpdateStatusStrip call.

How to run batched WCF service calls in Silverlight BackgroundWorker

Is there any existing plumbing to run WCF calls in batches in a BackgroundWorker?
Obviously since all Silverlight WCF calls are async - if I run them all in a backgroundworker they will all return instantly.
I just don't want to implement a nasty hack if theres a nice way to run service calls and collect the results.
Doesnt matter what order they are done in
All operations are independent
I'd like to have no more than 5 items running at once
Edit: i've also noticed (when using Fiddler) that no more than about 7 calls are able to be sent at any one time. Even when running out-of-browser this limit applies. Is this due to my default browser settings - or configurable also. obviously its a poor man's solution (and not suitable for what i want) but something I'll probably need to take account of to make sure the rest of my app remains responsive if i'm running this as a background task and don't want it using up all my connections.
I think your best bet would be to have your main thread put service request items into a Queue that is shared with a BackgroundWorker thread. The BackgroundWorker can then read from the Queue, and when it detects a new item, initiate the async WCF service request, and setup to handle the AsyncCompletion event. Don't forget to lock the Queue before you call Enqueue() or Dequeue() from different threads.
Here is some code that suggests the beginning of a solution:
using System;
using System.Collections.Generic;
using System.ComponentModel;
namespace MyApplication
{
public class RequestItem
{
public string RequestItemData { get; set; }
}
public class ServiceHelper
{
private BackgroundWorker _Worker = new BackgroundWorker();
private Queue<RequestItem> _Queue = new Queue<RequestItem>();
private List<RequestItem> _ActiveRequests = new List<RequestItem>();
private const int _MaxRequests = 3;
public ServiceHelper()
{
_Worker.DoWork += DoWork;
_Worker.RunWorkerAsync();
}
private void DoWork(object sender, DoWorkEventArgs e)
{
while (!_Worker.CancellationPending)
{
// TBD: Add a N millisecond timer here
// so we are not constantly checking the Queue
// Don't bother checking the queue
// if we already have MaxRequests in process
int _NumRequests = 0;
lock (_ActiveRequests)
{
_NumRequests = _ActiveRequests.Count;
}
if (_NumRequests >= _MaxRequests)
continue;
// Check the queue for new request items
RequestItem item = null;
lock (_Queue)
{
RequestItem item = _Queue.Dequeue();
}
if (item == null)
continue;
// We found a new request item!
lock (_ActiveRequests)
{
_ActiveRequests.Add(item);
}
// TBD: Initiate an async service request,
// something like the following:
try
{
MyServiceRequestClient proxy = new MyServiceRequestClient();
proxy.RequestCompleted += OnRequestCompleted;
proxy.RequestAsync(item);
}
catch (Exception ex)
{
}
}
}
private void OnRequestCompleted(object sender, RequestCompletedEventArgs e)
{
try
{
if (e.Error != null || e.Cancelled)
return;
RequestItem item = e.Result;
lock (_ActiveRequests)
{
_ActiveRequests.Remove(item);
}
}
catch (Exception ex)
{
}
}
public void AddRequest(RequestItem item)
{
lock (_Queue)
{
_Queue.Enqueue(item);
}
}
}
}
Let me know if I can offer more help.

OpenNetCF FTP class multithreading question

Currently, I have something like:
public partial class Form1 : Form
{
delegate void StringDelegate(string value);
private FTP m_ftp;
public Form1()
{
InitializeComponent();
}
private void connect_Click(object sender, EventArgs e)
{
OnResponse("Connecting");
m_ftp = new FTP(server.Text);
m_ftp.ResponseReceived += new FTPResponseHandler(m_ftp_ResponseReceived);
m_ftp.Connected += new FTPConnectedHandler(m_ftp_Connected);
m_ftp.BeginConnect(user.Text, password.Text);
}
void m_ftp_Connected(FTP source)
{
// when this happens we're ready to send command
OnResponse("Connected.");
}
void m_ftp_ResponseReceived(FTP source, FTPResponse Response)
{
OnResponse(Response.Text);
}
private void OnResponse(string response)
{
if (this.InvokeRequired)
{
this.Invoke(new StringDelegate(OnResponse), new object[] { response } );
return;
}
}
private void getFileList_Click(object sender, EventArgs e)
{
FTPFiles files = m_ftp.EnumFiles();
fileList.Items.Clear();
foreach (FTPFile file in files)
{
fileList.Items.Add( new ListViewItem( new string[] { file.Name, file.Size.ToString() } ));
}
tabs.SelectedIndex = 1;
}
private void upload_Click(object sender, EventArgs e)
{
FileStream stream = File.OpenRead("\\My Documents\\My Pictures\\Waterfall.jpg");
m_ftp.SendFile(stream, "waterfall.jpg");
stream.Close();
}
Which works fine - this example was taken from the samples. However, after a recent re-visit I have a question. In this particular case since OnResponse() function doesn't update the UI, it seems to serve no purpose here. I removed it (as well as all the calls to it) and it still works like before. Am I missing something?
After reading up more about multi threading with forms, I came to understand that this mechanism (demonstrated in the code above) is there to make sure the UI is responsive.
So in case when we need to say, update a UI element (such as textbox, label etc) we would have OnResponse implemented as follows:
delegate void StringDelegate(string dummy);
void OnResponse(string dummy)
{
if(!InvokeRequired)
{
button1.Text = dummy;
}
else
Invoke(new StringDelegate(OnResponse),new object[] {enabled});
}
If this function is implemented as:
delegate void StringDelegate(string dummy);
void OnResponse(string dummy)
{
if(InvokeRequired)
{
Invoke(new StringDelegate(OnResponse),new object[] {dummy});
return;
}
}
What's the use to have it at all? Is it absolutely necessary?
And another question: is ftp object running on its own thread here?
The FTP object is definitely running on its own thread. How do I know? This line:
m_ftp.BeginConnect(user.Text, password.Text);
This is an asynchronous method. Once you call this, the FTP component will use a thread from the .NET threadpool to do all of the work. This dedicated thread is the one that is used to "raise" the events. Ultimately a "raised event" is just one or more method calls to all of the delegates added to the event invocation list; it is this dedicated thread spun up by the Begin method that calls these methods. This thread is not the same thread as the thread that runs the UI, hence the need for the Invoke calls.
If you want the FTP component to use the UI thread, you'd use the Connect method instead of the BeginConnect method. This means your events wont work either, nor will your UI respond to interaction - this is completely expected because a thread can only do one thing at a time: it's either servicing the UI, or executing the FTP code. This is why you need a 2nd thread.
Make sense?
-Oisin

Resources