How to access Thread Name from Other function? - c#

I want to access the thread from other function in the same class.
For example
private void timer1_Tick(object sender, EventArgs e)
{
Thread thread1 = new Thread(new ThreadStart(Send1));
thread1.Start();
}
private void stop_btn_Click(object sender, EventArgs e)
{
thread1.Stop();
}
I wan to access thead1 from stop_btn_Click event. Both functions are in the same class Form1.

Declare private Thread thread1; on the class level rather than method
class ClassName
{
private Thread workerThread = null;
private void timer1_Tick(object sender, EventArgs e)
{
this.workerThread = new Thread(new ThreadStart(Send1));
workerThread.Start();
}
private void stop_btn_Click(object sender, EventArgs e)
{
this.workerThread.Stop();
}
}
By looking at the method name timer1_Tick() I can assume that you are simulating a timer behaviour. Take a look at the System.Timers.Timer and System.Threading.Timer classes perhaps you'll find them more useful for your case.

You need to store the thread in a private field in the form.
You also need to figure out what should happen if the user clicks Start twice; you may want to check whether the thread is already running, or use a list of threads.

you could take the variable outside the method (moving it into the class as a field):
private Thread thread1 = null;
void timer1_Tick(object sender, EventArgs e)
{
thread1 = new Thread(new ThreadStart(Send1));
thread1.Start();
}
private void stop_btn_Click(object sender, EventArgs e)
{
if (thread1 != null)
thread1.Stop();
}

Related

How to call this method in a background worker?

I am a beginner in C# and WPF and I am building this project in which I have to trigger when the mouse is moved. Under some conditions, I have to use it as a background worker. I want to call the mouse_Moved method in the background, but I don't know how to actually do that . Can anyone help me please? This is my code so far:
public MainWindow()
{
InitializeComponent();
mouse = new MouseInput();
mouse.MouseMoved += mouse_MouseMoved;
}
void mouse_MouseMoved(object sender, EventArgs e)
{
//The code that I need
}
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
//where I want to call the mouse_Moved method
}
Create a method and call it from both:
void mouse_MouseMoved(object sender, EventArgs e)
{
DoMouseMovedWork();
}
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
DoMouseMovedWork();
}
private DoMouseMovedWork()
{
//The code I need
}

Stopping Threading

I am new to winforms programming and I am starting to work with threads.
I have managed to start a thread, but now I want to be able to click on a cancel button to stop the thread.
Here is my code so far...
This starts the thread:
private void btnSessions_Click(object sender, EventArgs e)
{
Thread downloadThread = new Thread(new ThreadStart(DownloadThread));
downloadThread.Start();
}
This is the thread:
void DownloadThread()
{
// Do the work
}
This is the button I want to use to cancel the thread:
private void btnCancel_Click(object sender, EventArgs e)
{
// Stop the thread
}
Can anyone help me work out what I need to put in btnCancel_Click please?
You should use the Task Parallel Library (TPL) for this, which supports a natural way of canceling tasks:
private CancellationTokenSource _tokenSource2;
private CancellationToken _token;
private void btnSessions_Click(object sender, EventArgs e)
{
_tokenSource2 = new CancellationTokenSource();
_token = _tokenSource2.Token;
Task task = Task.Run(() => DownloadThread(), _token);
}
private void DownloadThread()
{
while (true)
{
//do work
//cancel if needed
if (_token.IsCancellationRequested)
{
_token.ThrowIfCancellationRequested();
}
}
}
private void btnCancel_Click(object sender, EventArgs e)
{
// Stop the thread
_tokenSource2.Cancel();
}
More about canceling tasks: http://msdn.microsoft.com/en-us/library/dd997396(v=vs.110).aspx
Why you should not use Thread.Abort: What's wrong with using Thread.Abort()
You need to make the downloadThread a field in your object:
Thread downloadThread;
private void btnSessions_Click(object sender, EventArgs e)
{
downloadThread = new Thread(new ThreadStart(DownloadThread));
downloadThread.Start();
}
void DownloadThread()
{
// Do the work
}
private void btnCancel_Click(object sender, EventArgs e)
{
downloadThread.Abort();
}
A background worker would be a better solution for ui related processing.
It's better don't use Thread and especially Thread.Abort for task like this. C# has high abstract wrapper to hide threads. Just use Task and CancellationToken.
Here is example:
var cts = new CancellationTokenSource(); // define in class
CancellationToken ct = cts.Token;
private void btnSessions_Click(object sender, EventArgs e)
{
Task.Factory.StartNew(() => DownloadThread(), ct ); // start task
}
private void DownloadThread()
{
// You need to check this at some point where cancel may occur
if (ct.IsCancellationRequested)
ct.ThrowIfCancellationRequested();
}
private void btnCancel_Click(object sender, EventArgs e)
{
cancelToken.Cancel(false); // cancel task
}
More information can be found at msdn

Application is working or not

How should I know if an application is working or processing something? Lets say that I'm trying to write a huge data into a file, on that time the application is not responding. I want to know the application current status.
Use BackgroundWorker componenet to process huge data in background thread. Notify user about progress via ProgressChanged event.
Sample:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
backgroundWorker1.WorkerReportsProgress = true;
}
private void WriteDataButton_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 1; i <= numberOfIterations; i++)
{
// write part of data
backgroundWorker1.ReportProgress(i * 100 / numberOfIterations);
}
}
// This event handler updates the progress.
private void backgroundWorker1_ProgressChanged(
object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
// This event handler deals with the results of the background operation.
private void backgroundWorker1_RunWorkerCompleted(
object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("Huge data was written");
}
}

c#: controlling access to object from different threads

How do I control when a thread is permitted to access an object and when it is not.
For example, if I have situation like below, I want to make sure that when I am doing something with objFoo in my ButtonClick event, I should not be able to touch objFoo from my doSomethingWithObjFoo method.
private void button1_Click(object sender, EventArgs e) {
// doing something with objFoo
}
private void timer1_Tick(object sender, EventArgs e) {
Thread T = new Thread(new ThreadStart(doSomethingWithObjFoo));
T.Start();
}
private void doSomethingWithObjFoo(){
// doing something else with objFoo
}
The easiest way is perhaps to use lock:
private object _fooLock = new object();
private void button1_Click(object sender, EventArgs e) {
lock(_fooLock)
{
// doing something with objFoo
}
}
private void timer1_Tick(object sender, EventArgs e) {
Thread T = new Thread(new ThreadStart(doSomethingWithObjFoo));
T.Start();
}
private void doSomethingWithObjFoo(){
lock(_fooLock)
{
// doing something else with objFoo
}
}
There are other options as well, such as using a ReaderWriterLockSlim.
That what we use lock for.
Thread Synchronization is a must read.
public class TestThreading
{
private System.Object lockThis = new System.Object();
public void Process()
{
lock (lockThis)
{
// Access thread-sensitive resources.
}
}
}

C# Threads - Parent Access Problem

my aim is that in the function "Dummy" i can change the controls like labels etc of the form from which the thread is initiating..how to do it..please don't suggest completely different strategies or making a worker class etc...modify this if you can
Thread pt= new Thread(new ParameterizedThreadStart(Dummy2));
private void button1_Click(object sender, EventArgs e)
{
pt = new Thread(new ParameterizedThreadStart(Dummy2));
pt.IsBackground = true;
pt.Start( this );
}
public static void Dummy(........)
{
/*
what i want to do here is to access the controls on my form form where the
tread was initiated and change them directly
*/
}
private void button2_Click(object sender, EventArgs e)
{
if (t.IsAlive)
label1.Text = "Running";
else
label1.Text = "Dead";
}
private void button3_Click(object sender, EventArgs e)
{
pt.Abort();
}
}
}
what i plan is that i could do this in the "Dummy" function
Dummy( object p)
{
p.label1.Text = " New Text " ;
}
You could do this, supposing you're passing an instance of the form to the thread method using the t.Start(...) method:
private void Form_Shown(object sender)
{
Thread t = new Thread(new ParameterizedThreadStart(Dummy));
t.Start(this);
}
....
private static void Dummy(object state)
{
MyForm f = (MyForm)state;
f.Invoke((MethodInvoker)delegate()
{
f.label1.Text = " New Text ";
});
}
EDIT
Added thread start code for clarity.
You can't do this. You can only access a UI control on the same thread that created it.
See the System.Windows.Forms.Control.Invoke Method and the Control.InvokeRequired property.
Can use something like this:
private void UpdateText(string text)
{
// Check for cross thread violation, and deal with it if necessary
if (InvokeRequired)
{
Invoke(new Action<string>(UpdateText), new[] {text});
return;
}
// What the update of the UI
label.Text = text;
}
public static void Dummy(........)
{
UpdateText("New text");
}

Categories

Resources