How to Run a Simple Bit of Code in a New Thread

Best way to run a simple function on a new Thread?

Your question isn't very clear, I'm afraid. You can easily start a new thread with some code, using anonymous methods in C# 2, and lambda expressions in C# 3:

Anonymous method:

new Thread(delegate() {
getTenantReciept_UnitTableAdapter1.Fill(
rentalEaseDataSet1.GetTenantReciept_Unit);
}).Start();
new Thread(delegate() {
getTenantReciept_TenantNameTableAdapter1.Fill(
rentalEaseDataSet1.GetTenantReciept_TenantName);
}).Start();

Lambda expression:

new Thread(() =>
getTenantReciept_UnitTableAdapter1.Fill(
rentalEaseDataSet1.GetTenantReciept_Unit)
).Start();
new Thread(() =>
getTenantReciept_TenantNameTableAdapter1.Fill(
rentalEaseDataSet1.GetTenantReciept_TenantName)
).Start();

You can use the same sort of syntax for Control.Invoke, but it's slightly trickier as that can take any delegate - so you need to tell the compiler which type you're using rather than rely on an implicit conversion. It's probably easiest to write:

EventHandler eh = delegate
{
// Code
};
control.Invoke(eh);

or

EventHandler eh = (sender, args) =>
{
// Code
};
control.Invoke(eh);

As a side note, are your names really that long? Can you shorten them to get more readable code?

How to force a piece of code inside a thread to run uninterruptedly (keep it from being preempted by the OS)

No. You are running your code on preemptive OS so there is nothing in your power to prevent preemption.

What is your real problem? Try to describe the actual problem you have, why did you come up with this requirement, and then perhaps one can offer advice to your actual problem..

After update

Remember this simple rule of thumb for multi-threaded programming: threads are almost never the right answer, event driven programming almost always is. Unless you have CPU intensive computation than can scale-up on distinct data sets, there is seldom a need to add threads. Spawning a new thread (or Task) simply to wait for IO (navigate to URL...) is an anti-pattern. Unfortunately 99.999% of multi-threaded programming examples simply use threads to simplify the control flow.

With that in mind, consider using an event driven model, for example EventFiringWebDriver. You will only have one thread, you main thread, and react in it to your web driver events (URLs downloaded, tabs opened, etc etc).

How to ensure a portion of code is run by just one thread at a time

Yes, you can use lock for this. Create a private synchronization object in your class, acquire the lock on this object and only one thread at a time will be able to execute the code within the lock block.

class Foo
{
private readonly object syncObj = new object();

public void Blah()
{
lock (syncObj)
{
//only one thread at a time
//will execute this code
}
}
}

Run a new thread immediately

The simplest way is to just instantiate a Thread

Thread task = new Thread(()=>
{
try
{
ConnectToCodeManager();

string connectionString = ConfigurationManager.ConnectionStrings["DataBaseConnection"].ConnectionString;

SQLTrazabilidadStorage storage = new SQLTrazabilidadStorage(connectionString);

storage.SendAggregation(parentCode, codesManagerURL);
}
catch (Exception ex)
{
log.Error(string.Format("SendAggregation to TrzCodesManagerWS: {0}", ex.ToString()));
}
});
task.Start();

How to run method with delay in separate thread if condition is still valid

In SWT/JFace you can't call GUI operations on background threads (this is the same in most GUI systems).

For this I would use Display.timerExec to run a method after the two seconds. Set a flag if the user types something that the method can check. timerExec runs the code in the UI thread so there are no problems with background threads.

private boolean dataEntered;

...

dataEntered = false;

Display.getCurrent().timerExec(2_000, () -> {
if (!dataEntered && !getTextControl().isDisposed()) {
showErrorMessage("xxx");
}
});

... other code sets dataEntered = true if data is entered

The !getTextControl().isDisposed() check deals with the dialog being closed before the 2 seconds expires.

Flask using thread to run code after/alognside return

it does work, but since in your Hello function you return 'Hello' after the thread start, the return redirect("/goodbye") never makes it to the browser. But the processing in the background works, you can add some print statements in the long_running_task code and see the flask console for yourself:

@app.route("/hello")
def Hello():
thread = threading.Thread(target=long_running_task)
thread.start()
return 'hello'

def long_running_task():
print("long task started")
time.sleep(5)
print("long task ended")
return redirect("/goodbye")


Related Topics



Leave a reply



Submit