PC Async Threads [C#]

Absolute Zero

Former Staff
Sep 2, 2015
120
105
53
28
Async Threads Tutorial

About
Ever wanted to make a seperate thread that doesn't run constantly in c# for a simple task, such as sending web requests or loading a file? Well, this will teach you how to do it without a BackGroundWorker! This will also teach you how to set control values from another thread safely.

Pre-Requisites
In order to use Threads and different Thread tasks, you will need to import these 2 classes into your project. At the top of your project, include these:

Code:
using System.Threading;
using System.Threading.Tasks;
Step 1
First off, you will want to create a simple function with no paramters, like so:
Code:
private void doStuff()
{

}
This will be your thread, written as a method/function. Pretty simple, right? Inside of this method you will perform the code for your operation.

Step 2
Next, you will want to fill your thread with operations, so for instance:
Code:
private void doStuff()
{
    WebClient client = new WebClient();
    string resp = client.uploadString("http://www.examplesite.com/api_post.php", "GET", "user=zero&dev_id=00000000000");
}
Once you have what you want in there, its quite simple from here. In your control that handles starting the thread (like a button, or anything else) simply type this code out to execute the thread:
Code:
new Thread(new ThreadStart(doStuff)).Start();
When you click the button (or other control), it will run the thread once. If you need data that is retrieved within the thread, you can create a variable at the top of your class, and pass the data from the thread into the variable to be used elsewhere. You can get from controls in an async thread, but you cannot set values or properties to a control that is not on the thread. As for variables, you can access them from any thread.

Additional
So, let's say that you have a label that you want to set data to from a thread, but you keep getting an error in VS stating that you cannot set control values cross thread. You indeed can, but it takes a little extra work. For this we need to create a new function, and we need to do something called invoking. You can invoke control properties from another thread, but you cannot set them directly. Here is an example function that will set text onto a label from an async thread:
Code:
private void setLabelText(Label label, string text)
{
    if (label.InvokeRequired)
    {
        MethodInvoker mi = new MethodInvoker(() => label.Text = text);
        label.Invoke(mi);
    }
}
With this function, you can set virtually any label on your form from an async thread. This is how it would be used in a thread:
Code:
private void doStuff()
{
    WebClient client = new WebClient();
    string resp = client.uploadString("http://www.examplesite.com/api_post.php", "GET", "user=zero&dev_id=00000000000");
    setLabelText(yourLabelName, resp);
}
In this code snippet, we are taking the result of the webclient and invoking a text change on a label named "yourLabelName". This is how you set control properties from another thread the safe and efficient way!

Conclusion
Being able to create async threads on the fly is very simple, and extremely useful in many circumstances. It allows you to create heavy-loaded functions that once froze your program (such as offset searching for the PS3 Modders) that no longer damper the flow of your program, and still allow you to perform other tasks while the operation is being carried out! You can also make looping threads with this very easily, and it requires little work. This is far more efficient than creating a background worker to perform all your threaded tasks in my opinion, and a much better solution than that of using a timer.


I hope you guys take this knowledge and use it to better your programs! :)

Absolute Zero
 
Last edited:

Cain532

Happy Modding
RG Admin
Feb 23, 2015
1,299
683
123
USA
Thanks
Async Threads Tutorial

About
Ever wanted to make a seperate thread that doesn't run constantly in c# for a simple task, such as sending web requests or loading a file? Well, this will teach you how to do it without a BackGroundWorker! This will also teach you how to set control values from another thread safely.

Pre-Requisites
In order to use Threads and different Thread tasks, you will need to import these 2 classes into your project. At the top of your project, include these:

Code:
using System.Threading;
using System.Threading.Tasks;
Step 1
First off, you will want to create a simple function with no paramters, like so:
Code:
private void doStuff()
{

}
This will be your thread, written as a method/function. Pretty simple, right? Inside of this method you will perform the code for your operation.
Step 2
Next, you will want to fill your thread with operations, so for instance:
Code:
private void doStuff()
{
    WebClient client = new WebClient();
    string resp = client.uploadString("http://www.examplesite.com/api_post.php", "GET", "user=zero&dev_id=00000000000");
}
Once you have what you want in there, its quite simple from here. In your control that handles starting the thread (like a button, or anything else) simply type this code out to execute the thread:
Code:
new Thread(new ThreadStart(doStuff)).Start();
When you click the button (or other control), it will run the thread once. If you need data that is retrieved within the thread, you can create a variable at the top of your class, and pass the data from the thread into the variable to be used elsewhere. You can get from controls in an async thread, but you cannot set values or properties to a control that is not on the thread. As for variables, you can access them from any thread.

Additional
So, let's say that you have a label that you want to set data to from a thread, but you keep getting an error in VS stating that you cannot set control values cross thread. You indeed can, but it takes a little extra work. For this we need to create a new function, and we need to do something called invoking. You can invoke control properties from another thread, but you cannot set them directly. Here is an example function that will set text onto a label from an async thread:
Code:
private void setLabelText(Label label, string text)
{
    if (label.InvokeRequired)
    {
        MethodInvoker mi = new MethodInvoker(() => label.Text = text);
        label.Invoke(mi);
    }
}
With this function, you can set virtually any label on your form from an async thread. This is how it would be used in a thread:
Code:
private void doStuff()
{
    WebClient client = new WebClient();
    string resp = client.uploadString("http://www.examplesite.com/api_post.php", "GET", "user=zero&dev_id=00000000000");
    setLabelText(yourLabelName, resp);
}
In this code snippet, we are taking the result of the webclient and invoking a text change on a label named "yourLabelName". This is how you set control properties from another thread the safe and efficient way!
Conclusion
Being able to create async threads on the fly is very simple, and extremely useful in many circumstances. It allows you to create heavy-loaded functions that once froze your program (such as offset searching for the PS3 Modders) that no longer damper the flow of your program, and still allow you to perform other tasks while the operation is being carried out! You can also make looping threads with this very easily, and it requires little work. This is far more efficient than creating a background worker to perform all your threaded tasks in my opinion, and a much better solution than that of using a timer.


I hope you guys take this knowledge and use it to better your programs! :)

Absolute Zero
Thanks for this!!! I'm sure it'll help out a lot of people myself included
 

Absolute Zero

Former Staff
Sep 2, 2015
120
105
53
28
Thanks

Thanks for this!!! I'm sure it'll help out a lot of people myself included
No problem dude! I figured you of all people would like this, since I remember you asking me about threading and bg workers a while back :D
 

Cyb3r

RG Admin
RG Admin
Feb 21, 2015
1,657
852
123
Awesome tutorial man i'm sure this well get in handy for me someday :honored:
 

Cain532

Happy Modding
RG Admin
Feb 23, 2015
1,299
683
123
USA
No problem dude! I figured you of all people would like this, since I remember you asking me about threading and bg workers a while back :D
Definitely :p I found another way, very similar to this, it involves building a thread like that but it gets called in the Program.cs, calling the Thread like ConstantWrite.Start(); above the Application.Run(new Form1) and ConstantWrite.Abort() below that,
The whole thing looks like this;

Code:
public static Thread ConstantWrite = new Thread(new ThreadStart(CWrite));
public static bool toggle;
public static void CWrite()
{
bool sleep = false;
while (true)
{
//run code inside here, you can use bools to toggle, or ints.
if (toggle)
{
//do stuff;
}
if (!sleep)
     Thread.Sleep(100);
}
}
Your method looks nice and compact, very similar tho :D

Also, not sure if this helps, but if you declare your thread outside a button like it is above, you can then call it inside a button just by typing (in my case) ConstantWrite.Start(); :p
 

KranK

✮ ズ丂ム刀ズ ✮
RG Prime
May 27, 2015
346
387
73
29
Israel
www.csc-xsc.tk
Definitely :p I found another way, very similar to this, it involves building a thread like that but it gets called in the Program.cs, calling the Thread like ConstantWrite.Start(); above the Application.Run(new Form1) and ConstantWrite.Abort() below that,
The whole thing looks like this;

Code:
public static Thread ConstantWrite = new Thread(new ThreadStart(CWrite));
public static bool toggle;
public static void CWrite()
{
bool sleep = false;
while (true)
{
//run code inside here, you can use bools to toggle, or ints.
if (toggle)
{
//do stuff;
}
if (!sleep)
     Thread.Sleep(100);
}
}
Your method looks nice and compact, very similar tho :D

Also, not sure if this helps, but if you declare your thread outside a button like it is above, you can then call it inside a button just by typing (in my case) ConstantWrite.Start(); :p
Or you just could hook into any game adress and run your code inside it xD
 

Absolute Zero

Former Staff
Sep 2, 2015
120
105
53
28
Definitely :p I found another way, very similar to this, it involves building a thread like that but it gets called in the Program.cs, calling the Thread like ConstantWrite.Start(); above the Application.Run(new Form1) and ConstantWrite.Abort() below that,
The whole thing looks like this;

Code:
public static Thread ConstantWrite = new Thread(new ThreadStart(CWrite));
public static bool toggle;
public static void CWrite()
{
bool sleep = false;
while (true)
{
//run code inside here, you can use bools to toggle, or ints.
if (toggle)
{
//do stuff;
}
if (!sleep)
     Thread.Sleep(100);
}
}
Your method looks nice and compact, very similar tho :D

Also, not sure if this helps, but if you declare your thread outside a button like it is above, you can then call it inside a button just by typing (in my case) ConstantWrite.Start(); :p
Its the same thing but runs before the first form is loaded, its basically a manual bgw with a toggle because of the bool :p
 

Cain532

Happy Modding
RG Admin
Feb 23, 2015
1,299
683
123
USA
I was poking around and found that you can do a super easy setup like this as well

Code:
        public async void Do_The_Thing()
        {
            bool sleep = false;
            while (true)
            {
                //Do Stuff
                if (!sleep)
                    Thread.Sleep(100);
            }
        }
and call it like

Code:
Do_The_Thing();
if you keep the "while (true)" portion, it'll run forever. without it, it'll just run once. This method is super nice, because you don't have to worry about making public static variables for everything :p

Just found this today and wanted to share.
 
  • Like
Reactions: LEGACYY