Class

# Thread

<div class="rst-class">

forsearch

</div>

Multicore

<div class="rst-class">

forsearch

</div>

Preemptive

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

## Description

Threads execute code in the background.

## Properties

<div class="rst-class">

table-centered_columns_3_and_4

</div>

| Name                                      | Type                                | Read-Only | Shared |
|-------------------------------------------|-------------------------------------|-----------|--------|
| `Current<thread.current>`                 | Thread                              | ✓         | ✓      |
| `DebugIdentifier<thread.debugidentifier>` | `String</api/data_types/string>`    |           |        |
| `Priority<thread.priority>`               | `Integer</api/data_types/integer>`  |           |        |
| `StackSize<thread.stacksize>`             | `Integer</api/data_types/integer>`  |           |        |
| `Tag<thread.tag>`                         | `Variant</api/data_types/variant>`  |           |        |
| `ThreadID<thread.threadid>`               | `Integer</api/data_types/integer>`  | ✓         |        |
| `ThreadState<thread.threadstate>`         | `ThreadStates<thread.threadstates>` | ✓         |        |
| `Type<thread.type>`                       | `Types<thread.types>`               |           |        |

## Methods

<div class="rst-class">

table-centered_column_4

</div>

| Name                                                    | Parameters                                                                                                                                                                                                                                                                                       | Returns | Shared |
|---------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------|--------|
| `AddUserInterfaceUpdate<thread.adduserinterfaceupdate>` | data As `Dictionary</api/language/dictionary>`                                                                                                                                                                                                                                                   |         |        |
|                                                         | `ParamArray</api/language/paramarray>` data As `Pair</api/language/pair>`                                                                                                                                                                                                                        |         |        |
| `Pause<thread.pause>`                                   |                                                                                                                                                                                                                                                                                                  |         |        |
| `Resume<thread.resume>`                                 |                                                                                                                                                                                                                                                                                                  |         |        |
| `Sleep<thread.sleep>`                                   | milliseconds As `Integer</api/data_types/integer>`, wakeEarly As `Boolean</api/data_types/boolean>` = `False</api/language/false>`                                                                                                                                                               |         |        |
| `SleepCurrent<thread.sleepcurrent>`                     | milliseconds As `Integer</api/data_types/integer>`                                                                                                                                                                                                                                               |         | ✓      |
| `Start<thread.start>`                                   |                                                                                                                                                                                                                                                                                                  |         |        |
| `StartMethod<thread.startmethod>`                       | start As `StartMethod<thread.startmethod_delegate>`, type As `Thread.Types<thread.types>` = `Thread.Types<thread.types>`.Cooperative, completion As `Thread.StartMethodCompleted<thread.startmethodcompleted>` = `Nil</api/language/nil>`                                                        |         |        |
|                                                         | method As `StartMethodWithValue<thread.startmethodwithvalue>`, value as `Variant</api/data_types/variant>`, type As `Thread.Types<thread.types>` = `Thread.Types<thread.types>`.Cooperative, completion As `Thread.StartMethodCompleted<thread.startmethodcompleted>` = `Nil</api/language/nil>` |         |        |
| `Stop<thread.stop>`                                     |                                                                                                                                                                                                                                                                                                  |         |        |
| `YieldToNext<thread.yieldtonext>`                       |                                                                                                                                                                                                                                                                                                  |         | ✓      |

## Events

<div class="rst-class">

table-centered_column_4

</div>

| Name                                              | Parameters                                       | Returns |
|---------------------------------------------------|--------------------------------------------------|---------|
| `Run<thread.run>`                                 |                                                  |         |
| `UserInterfaceUpdate<thread.userinterfaceupdate>` | data() As `Dictionary</api/language/dictionary>` |         |

## Delegate Methods

<div class="rst-class">

table-centered_column_4

</div>

| Name                                                | Parameters                                  | Returns                            |
|-----------------------------------------------------|---------------------------------------------|------------------------------------|
| `StartMethod<thread.startmethod_delegate>`          |                                             | `Variant</api/data_types/variant>` |
| `StartMethodCompleted<thread.startmethodcompleted>` | value As `Variant</api/data_types/variant>` |                                    |
| `StartMethodWithValue<thread.startmethodwithvalue>` | value As `Variant</api/data_types/variant>` | `Variant</api/data_types/variant>` |

## Constants

### Priority

> The following class constants can be used to set the priority of the <span class="title-ref">Thread</span> with the Priority property.
>
> | Class Constant | Value | Description                           |
> |----------------|-------|---------------------------------------|
> | LowestPriority | 1     | Lowest priority                       |
> | NormalPriority | 5     | Normal priority (same as Main thread) |
> | HighPriority   | 10    | High priority                         |
>
> These values are totalled, then divided by the main <span class="title-ref">Thread</span> and divvied out by proportion, but the main <span class="title-ref">Thread</span> always has a priority of five, so using very large numbers for other Threads will potentially starve the main <span class="title-ref">Thread</span>. For example, if you give a second <span class="title-ref">Thread</span> a priority of 500, there will be a total 505 slots in the scheduler and five of those belong to the main <span class="title-ref">Thread</span>. Read more about priority below.

## Enumerations

<div id="thread.types">

<div class="rst-class">

forsearch

</div>

</div>

Thread.Types

### Types

> The different types a <span class="title-ref">Thread</span> can be.
>
> | Enum        | Description                                                                                                                                                    |
> |-------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------|
> | Cooperative | The <span class="title-ref">Thread</span> shares time with all other cooperative Threads as well the app itself, all of which run on a single core of the CPU. |
> | Preemptive  | The <span class="title-ref">Thread</span> can run on a core separate from other preemptive Threads and the app itself.                                         |

<div id="thread.threadstates">

<div class="rst-class">

forsearch

</div>

</div>

Thread.ThreadStates

### ThreadStates

> Specifies all possible states a <span class="title-ref">Thread</span> can be in.
>
> | Enum       | Description                                                                                                                                                                                                                                                                        |
> |------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
> | Running    | The code is executing.                                                                                                                                                                                                                                                             |
> | Waiting    | The <span class="title-ref">Thread</span> has been blocked by a call to Signal or Enter from one of the locking mechanisms, `CriticalSection</api/language/threading/criticalsection>`, `Mutex</api/language/threading/mutex>`, or `Semaphore</api/language/threading/semaphore>`. |
> | Paused     | The code has halted because the `Pause<thread.pause>` method was called.                                                                                                                                                                                                           |
> | Sleeping   | The code has halted because the `Sleep<thread.sleep>` method was called.                                                                                                                                                                                                           |
> | NotRunning | The code is not running the `Start<thread.start>` method has not yet been called or the code has already finished running.                                                                                                                                                         |

## Property descriptions

<div id="thread.current">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Thread.Current

**Current** As **Thread**

> Returns the <span class="title-ref">Thread</span> that was executing at the moment this property was read.
>
> This property is read-only.
>
> This property is `shared</api/language/shared>`.
>
> This property is `Nil</api/language/nil>` when accessed from the main <span class="title-ref">Thread</span>.
>
> <div class="important">
>
> <div class="title">
>
> Important
>
> </div>
>
> This property is not supported for Android.
>
> </div>

<div id="thread.debugidentifier">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Thread.DebugIdentifier

**DebugIdentifier** As `String</api/data_types/string>`

> Identifier which will show up in the debugger's <span class="title-ref">Thread</span> popup.

<div id="thread.priority">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Thread.Priority

**Priority** As `Integer</api/data_types/integer>`

> Gets and sets the relative priority of the <span class="title-ref">Thread</span>.
>
> <div class="note">
>
> <div class="title">
>
> Note
>
> </div>
>
> On Android this property is only supported for preemptive threads.
>
> </div>
>
> The Priority can be changed while a <span class="title-ref">Thread</span> is running.
>
> The application's main <span class="title-ref">Thread</span> has a priority of 5 and this is also the default value of any programmatically created Threads. If you don't modify this value, your application will behave normally, in the sense that all the threads will share the CPU's resources equally.
>
> Increasing the value of *Priority* above 5 gives that <span class="title-ref">Thread</span> more processing cycles than other Threads. Doubling the value of *Priority* will double the number of processing cycles the <span class="title-ref">Thread</span> gets. A <span class="title-ref">Thread</span> with a *Priority* of 1 will get one-fifth the processing cycles as the main <span class="title-ref">Thread</span>. The range is 1 to 2^31-1, but very high values of *Priority* will make it difficult for other Threads to run at all. The value of *Priority* changes the way in which Threads get processing cycles only if their values are not all equal. You can use the following class constants to assign to *Priority* or to compare its value:
>
> | Value | Description    |
> |-------|----------------|
> | 1     | LowestPriority |
> | 5     | NormalPriority |
> | 10    | HighPriority   |
>
> You do not need to use these constants; you can use any legal integer value instead.
>
> This example lowers the priority of the <span class="title-ref">Thread</span> prior to calling its `Start<thread.start>` method.
>
> ``` xojo
> Thread1.Priority = Thread.LowestPriority
> Thread1.Start
> ```

<div id="thread.stacksize">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Thread.StackSize

**StackSize** As `Integer</api/data_types/integer>`

> The size of the stack, in bytes.
>
> <div class="important">
>
> <div class="title">
>
> Important
>
> </div>
>
> This property is not supported for Android.
>
> </div>
>
> The StackSize can only be set when the <span class="title-ref">Thread</span> is not running. The default stack size is 512KB on macOS and Linux and 1MB on Windows. A StackSize of zero indicates the default is used.
>
> There is generally little reason to change this. Each stack frame only need to contain information about the parameters, local variables and return address for a method call. This does not include memory needed for objects. It would take a significant amount of local variables or parameters with method calls that are 100s of levels deep in order to exhaust the stack space.
>
> ``` xojo
> Thread1.StackSize = 96000
> ```

<div id="thread.tag">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Thread.Tag

**Tag** As `Variant</api/data_types/variant>`

> A "hidden" value associated with the <span class="title-ref">Thread</span>.
>
> This example is in the Opening event of the main window.
>
> ``` xojo
> MyThread.Tag = "Additional information"
> ```

<div id="thread.threadid">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Thread.ThreadID

**ThreadID** As `Integer</api/data_types/integer>`

> ID of the <span class="title-ref">Thread</span>, assigned at runtime.
>
> This property is read-only.
>
> <div class="note">
>
> <div class="title">
>
> Note
>
> </div>
>
> `ThreadID<thread.threadid>` will be non-zero only when the <span class="title-ref">Thread</span> is running.
>
> </div>
>
> This example reports the ThreadID only if the <span class="title-ref">Thread</span> is running.
>
> ``` xojo
> If LongProcessThread1.State <> Thread.NotRunning Then
>   MessageBox(LongProcessThread1.ThreadID.ToString)
> Else
>   MessageBox("The thread is not running!")
> End If
> ```

<div id="thread.threadstate">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Thread.ThreadState

**ThreadState** As `ThreadStates<thread.threadstates>`

> Indicates the state of the <span class="title-ref">Thread</span>.
>
> This property is read-only.
>
> A <span class="title-ref">Thread</span> can be in one of five states. See `ThreadStates<thread.threadstates>` for details.
>
> This window method checks the State of the <span class="title-ref">Thread</span> and displays a message in a `TextField</api/user_interface/desktop/desktoptextfield>` on the form. The parameter is:
>
> ``` xojo
> State As Thread.ThreadStates
> ```
>
> ``` xojo
> Select Case State
> Case Thread.ThreadStates.Running
>   TextField1.Text = "Running"
> Case Thread.ThreadStates.Waiting
>   TextField1.Text = "Waiting"
> Case Thread.ThreadStates.Sleeping
>   TextField1.Text = "Sleeping"
> Case Thread.ThreadStates.Paused
>   TextField1.Text = "Paused"
> Case Thread.ThreadStates.NotRunning
>   TextField1.Text = "Not Running"
> End Select
> ```

<div id="thread.type">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Thread.Type

**Type** As `Types<thread.types>`

> Indicates the type of the <span class="title-ref">Thread</span>, Cooperative or Preemptive. Cooperative is the default.
>
> Carefully read the `Preemptive Threads<thread.preemptive_threads>` notes before using them.
>
> <div class="important">
>
> <div class="title">
>
> Important
>
> </div>
>
> On Android, this property cannot be changed while the <span class="title-ref">Thread</span> is running. Doing so will raise an `UnsupportedOperationException</api/exceptions/unsupportedoperationexception>`.
>
> </div>

## Method descriptions

<div id="thread.adduserinterfaceupdate">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Thread.AddUserInterfaceUpdate

**AddUserInterfaceUpdate**(data As `Dictionary</api/language/dictionary>`)

**AddUserInterfaceUpdate**(`ParamArray</api/language/paramarray>` data As `Pair</api/language/pair>`)

> Triggers the `UserInterfaceUpdate<thread.userinterfaceupdate>` event so you can update your user interface from the <span class="title-ref">Thread</span>. This method is safe to call from a preemptive <span class="title-ref">Thread</span>.

<div id="thread.pause">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Thread.Pause

**Pause**

> Puts the <span class="title-ref">Thread</span> in a paused state. Every call to Pause must be matched by a call to Resume.
>
> The <span class="title-ref">Thread</span> will not be allocated any processing cycles, regardless of its assigned *Priority*. It is “asleep.” To wake it up, call the Resume method. If the <span class="title-ref">Thread</span> is executing when you call Pause, it will immediately cause a context switch.
>
> This example calls Pause, followed by a call to Resume after other code has executed.
>
> ``` xojo
> LongProcessThread1.Pause
> ' do something else here...
> LongProcessThread1.Resume
> ```
>
> <div class="important">
>
> <div class="title">
>
> Important
>
> </div>
>
> <span class="title-ref">Pause</span> is not supported for cooperative threads on Android. Calling it will raise an `UnsupportedOperationException</api/exceptions/unsupportedoperationexception>`.
>
> </div>

<div id="thread.resume">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Thread.Resume

**Resume**

> Wakes up a <span class="title-ref">Thread</span> that was paused because of a call to `Thread.Pause<thread.pause>` or is sleeping because of a call to `Thread.Sleep<thread.sleep>`. Every call to Pause must be matched by a call to Resume.
>
> When you call Resume, the <span class="title-ref">Thread</span> reacquires its ability to receive processing cycles according to its value of *Priority*. Calling Resume will not cause a context switch to take place, that is, a switch to the next <span class="title-ref">Thread</span> in the queue.
>
> <div class="important">
>
> <div class="title">
>
> Important
>
> </div>
>
> <span class="title-ref">Resume</span> is not supported for cooperative threads on Android. Calling it will raise an `UnsupportedOperationException</api/exceptions/unsupportedoperationexception>`.
>
> </div>
>
> ``` xojo
> LongProcessThread1.Resume
> ```

<div id="thread.sleep">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Thread.Sleep

**Sleep**(milliseconds As `Integer</api/data_types/integer>`, WakeEarly As `Boolean</api/data_types/boolean>` = `False</api/language/false>`)

> Puts the <span class="title-ref">Thread</span> to sleep for the specified amount of time.
>
> By default, *wakeEarly* is `False</api/language/false>`. In this state, the <span class="title-ref">Thread</span> will be put to sleep for the full amount of time specified by *milliseconds*. If you set *wakeEarly* to `True</api/language/true>`, the <span class="title-ref">Thread</span> can be resumed early. It will wake up early if there are no other Threads able to execute.
>
> Calling this method when the <span class="title-ref">Thread</span> is already sleeping will result in the <span class="title-ref">Thread</span> instead sleeping for the *milliseconds* specified by the most recent call.
>
> ``` xojo
> LongProcessThread1.Sleep(300, True)
> ```

<div id="thread.sleepcurrent">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Thread.SleepCurrent

**SleepCurrent**(milliseconds As `Integer</api/data_types/integer>`)

> Sleeps the currently executing <span class="title-ref">Thread</span> for the specified number of *milliseconds*.
>
> This method is `shared</api/language/shared>`.
>
> If the currently executing <span class="title-ref">Thread</span> is the main <span class="title-ref">Thread</span>, it will sleep like any other <span class="title-ref">Thread</span> would.

<div id="thread.start">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Thread.Start

**Start**

> Starts the <span class="title-ref">Thread</span>'s Run event handler.

<div id="thread.startmethod">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Thread.StartMethod

**StartMethod**(start As `StartMethod<thread.startmethod_delegate>`, type As `Thread.Types<thread.types>` = `Thread.Types<thread.types>`.Cooperative, completion As `Thread.StartMethodCompleted<thread.startmethodcompleted>` = `Nil</api/language/nil>`)

> A convenient way of running a method in a <span class="title-ref">Thread</span> without the need for a <span class="title-ref">Thread</span> subclass.
>
> Starts *start* as the *type* of thread specified. If a *completion* method is provided, it will be called with the thread ends.
>
> The *start* and *completion* methods are `delegates</api/data_types/additional_types/delegate>`. This means the parameter must use `AddressOf</api/language/addressof>` or be a function that returns a `delegate</api/data_types/additional_types/delegate>`.
>
> <div class="important">
>
> <div class="title">
>
> Important
>
> </div>
>
> This method is not supported for Android.
>
> </div>

**StartMethod**(start As `StartMethodWithValue<thread.startmethodwithvalue>`, value as `Variant</api/data_types/variant>`, type As `Thread.Types<thread.types>` = `Thread.Types<thread.types>`.Cooperative, completion As `Thread.StartMethodCompleted<thread.startmethodcompleted>` = `Nil</api/language/nil>`)

> Starts *start*, passing the *value*, as the *type* of thread specified. If a *completion* method is provided, it will be called with the thread ends.
>
> The *start* and *completion* methods are `delegates</api/data_types/additional_types/delegate>`. This means the parameter must use `AddressOf</api/language/addressof>` or be a function that returns a `delegate</api/data_types/additional_types/delegate>`.
>
> This example passes the LoadPictures method as the method that will run in the thread, passes a picFolder (a `FolderItem</api/files/folderitem>` as the value parameter, indicates it will be a preemptive thread and passes LoadPicturesCompleted as the *completion* method):
>
> ``` xojo
> Thread.StartMethod(AddressOf LoadPictures, picFolder, Thread.Types.Preemptive, AddressOf LoadPicturesCompleted)
> ```
>
> <div class="note">
>
> <div class="title">
>
> Note
>
> </div>
>
> The *completion* method, if provided, executes in the main thread.
>
> </div>
>
> <div class="important">
>
> <div class="title">
>
> Important
>
> </div>
>
> This method is not supported for Android.
>
> </div>

<div id="thread.stop">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Thread.Stop

**Stop**

> Stops the specified <span class="title-ref">Thread</span>.
>
> Internally, this method will cause your <span class="title-ref">Thread</span>'s stack to unwind, destructors for local objects to be called, and so forth. It's a graceful exit which can cause code to execute. It may also cause context switches.
>
> <div class="note">
>
> <div class="title">
>
> Note
>
> </div>
>
> A <span class="title-ref">Thread</span> should not stop itself. Instead, just return from the Run event handler to allow the <span class="title-ref">Thread</span> to end.
>
> </div>
>
> This example, which is in the Pressed event of a button, stops the <span class="title-ref">Thread</span>.
>
> ``` xojo
> LongProcessThread1.Stop
> ```

<div id="thread.yieldtonext">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Thread.YieldToNext

**YieldToNext**

> Causes the current <span class="title-ref">Thread</span> to yield its time to the next <span class="title-ref">Thread</span>.
>
> This method is `shared</api/language/shared>`.
>
> This causes the <span class="title-ref">Thread</span> Scheduler to yield the currently executing <span class="title-ref">Thread</span>'s processing time to the next <span class="title-ref">Thread</span> in the queue that is awaiting processing cycles. It is possible for the next <span class="title-ref">Thread</span> to be the currently executing <span class="title-ref">Thread</span>.

## Event descriptions

<div id="thread.run">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Thread.Run

**Run**

> The Start method has been called. The threaded code is placed in this event handler. Methods called from here also run in the <span class="title-ref">Thread</span>.
>
> MacOS apps cannot access the user interface from within a <span class="title-ref">Thread</span>. Doing so raises a `ThreadAccessingUIException</api/exceptions/threadaccessinguiexception>`. Instead, use the `AddUserInterfaceUpdate<thread.adduserinterfaceupdate>` method in conjunction with the `UserInterfaceUpdate<thread.userinterfaceupdate>` event. See the `UserInterfaceUpdate<thread.userinterfaceupdate>` event for an example.

<div id="thread.userinterfaceupdate">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Thread.UserInterfaceUpdate

**UserInterfaceUpdate**(data() As `Dictionary</api/language/dictionary>`)

> Used to update your app's user interface.
>
> Apps cannot access the user interface from within the `Run<thread.run>` event of a <span class="title-ref">Thread</span>. Doing so raises a `ThreadAccessingUIException</api/exceptions/threadaccessinguiexception>`. Instead, use the UserInterfaceUpdate event to update your user interface. It can be triggered by calling the `AddUserInterfaceUpdate<thread.adduserinterfaceupdate>` method from within the `Run<thread.run>` event.
>
> Each call to `AddUserInterfaceUpdate<thread.adduserinterfaceupdate>` in the `Run<thread.run>` event, adds the values passed to an array that is then passed to the UserInterfaceUpdate event (the data() parameter above). This allows you to process all of the calls to `AddUserInterfaceUpdate<thread.adduserinterfaceupdate>` or just the most recent one. For example, if your <span class="title-ref">Thread</span> was reading a series of files and you wished to add the name of each file read to a `ListBox</api/user_interface/desktop/desktoplistbox>`, you'd want to read each row of the data() array passed to this event. However, if you instead were only displaying a `ProgressBar</api/user_interface/desktop/desktopprogressbar>` and wanted to show how far you'd gotten through reading all the files, it would be more efficient to read the last item of the data() array passed to this event and then update your `ProgressBar</api/user_interface/desktop/desktopprogressbar>` control rather than iterate through all of the items in the data() array.
>
> This code (in the UserInterfaceUpdate event) updates a ProgressBar (called UIProgress) on a Window:
>
> ``` xojo
> For Each update As Dictionary In data
>   If update.HasKey("UIProgress") Then
>     UIProgress.Value = update.Value("UIProgress").IntegerValue
>   End If
> Next
> ```
>
> The Data parameter is an array of Dictionaries containing information supplied by the `AddUserInterfaceUpdate<thread.adduserinterfaceupdate>` method that can be used to update the UI.
>
> The `Run<thread.run>` event contains the code that runs in the <span class="title-ref">Thread</span> and calls `AddUserInterfaceUpdate<thread.adduserinterfaceupdate>` with any necessary information:
>
> ``` xojo
> Var progressValue As Integer
>
> While progressValue < 100
>   progressValue = progressValue + 1
>
>   //Your processing code goes here. For the sake of this example
>   //we've added a dummy loop below so you can see the progress bar update.
>
>   ' Do nothing for 1/4 second
>   Var waitUntil As Integer = System.Ticks + 15
>   While System.Ticks < waitUntil
>   Wend
>
>   ' Call AddUserInterfaceUpdate with any parameters you need. This calls the UserInterfaceUpdate event handler
>   ' where you can directly access any UI controls on the Window.
>
>   ' This specifies simple parameters using a Pair
>   ' You can also pass values using a Dictionary
>   Me.AddUserInterfaceUpdate("UIProgress" : progressValue)
>
> Wend
> ```

## Delegate descriptions

<div id="thread.startmethod_delegate">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Thread.StartMethod

**StartMethod** As `Variant</api/data_types/variant>`

> Any method that returns a `Variant</api/data_types/variant>`, but does not have a parameter, can be used with `StartMethod<thread.startmethod>`.
>
> <div class="important">
>
> <div class="title">
>
> Important
>
> </div>
>
> This delegate is not supported for Android.
>
> </div>

<div id="thread.startmethodcompleted">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Thread.StartMethodCompleted

**StartMethodCompleted**(value As `Variant</api/data_types/variant>`)

> Any method that includes a `Variant</api/data_types/variant>` parameter can be used as the completion for `StartMethod<thread.startmethod>`.
>
> <div class="important">
>
> <div class="title">
>
> Important
>
> </div>
>
> This delegate is not supported for Android.
>
> </div>

<div id="thread.startmethodwithvalue">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Thread.StartMethodWithValue

**StartMethodWithValue**(value As `Variant</api/data_types/variant>`) As `Variant</api/data_types/variant>`

> Any method that returns a `Variant</api/data_types/variant>`, and has a `Variant</api/data_types/variant>` parameter, can be used with `StartMethod<thread.startmethod>`.
>
> <div class="important">
>
> <div class="title">
>
> Important
>
> </div>
>
> This delegate is not supported for Android.
>
> </div>

## Notes

Threads stay in scope as long as they are active, even if the variable or property referring to the <span class="title-ref">Thread</span> goes out of scope.

<div class="warning">

<div class="title">

Warning

</div>

`Runtime.IterateObjects<runtime.iterateobjects>` is not safe to use in a preemptive <span class="title-ref">Thread</span>.

</div>

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

### Updating the user interface from a <span class="title-ref">Thread</span>

<div class="warning">

<div class="title">

Warning

</div>

Do not access any built-in property or method of a user interface control or Window from a <span class="title-ref">Thread</span>'s `Run<thread.run>` event or any methods called from it as platform UI frameworks (macOS, Windows and Linux) are not <span class="title-ref">Thread</span>-safe. Doing so raises a `ThreadAccessingUIException</api/exceptions/threadaccessinguiexception>`. See below for additional information.

</div>

Your application code normally runs in the so-called main <span class="title-ref">Thread</span> which is the <span class="title-ref">Thread</span> responsible for managing events in the user interface. If you have a long-running process that runs in the main <span class="title-ref">Thread</span>, the user interface will not update and will be unresponsive to the user.

Typically, you use the <span class="title-ref">Thread</span> class to run code that will not affect the state of the user interface. This also means that code that runs in these Threads cannot access the user interface. Doing so raises a `ThreadAccessingUIException</api/exceptions/threadaccessinguiexception>`.

Essentially, a <span class="title-ref">Thread</span> is used to allow a very time-consuming process to run in the background. There may be times where you want to update the user interface with something that has been processed in the <span class="title-ref">Thread</span>. The way to do this is by putting the code that updates your user interface in the `UserInterfaceUpdate<thread.userinterfaceupdate>` event and triggering it from the `Run<thread.run>` event by calling the `AddUserInterfaceUpdate<thread.adduserinterfaceupdate>` method inside the loop you likely have running in your `Run<thread.run>` event handler.

Keep in mind that a <span class="title-ref">Thread</span> can access your own properties and methods that are part of UI controls or Windows as long as they do not in turn access your app's user interface controls.

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

### Safely sharing resources between Threads

Sometimes you may have a resource (data or a file, for example) that needs to be used by multiple Threads that are all currently running. An example would be that a <span class="title-ref">Thread</span> tries to open a file for writing that another <span class="title-ref">Thread</span> has already opened for writing. This can cause issues and unwanted exceptions.

You can manage this by using a `CriticalSection</api/language/threading/criticalsection>`, `Semaphore</api/language/threading/semaphore>` or `Mutex</api/language/threading/mutex>` to prevent multiple Threads from trying to access the same shared resource.

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

### How cpu time is shared between Threads

Threads are managed by the built-in <span class="title-ref">Thread</span> Scheduler. Its task is to allocate the CPU's processing cycles among all of the application's Threads. Note that because Threads are cooperative, they all share the CPU cycles of a single CPU core. Threads cannot access other CPU cores. The `Priority<thread.priority>` property determines how many or how few processing cycles the <span class="title-ref">Thread</span> gets, relative to the main <span class="title-ref">Thread</span> (which always has a priority of 5) and any other Threads that you have created. Use a higher value for Priority to give a <span class="title-ref">Thread</span> more CPU cycles and a lower value to give it less CPU cycles.

Threads run in the background, but are temporarily blocked by certain user actions:

- While the mouse button is held down,
- While a window is being dragged,
- While a menu in the menu bar is pulled down,
- While the mouse button is pressed on a control in a window (not true of Windows)

When the <span class="title-ref">Thread</span> Scheduler decides to stop execution of the current <span class="title-ref">Thread</span> and allow another <span class="title-ref">Thread</span> to run, it is called a *context switch*. The amount of time a <span class="title-ref">Thread</span> runs is called the *time slice* for the <span class="title-ref">Thread</span>.

Threads can yield time to other Threads and other applications each time they execute a looping construct such as `For</api/language/loops/for...next>`, `While</api/language/loops/while...wend>`, and `Do...Loop</api/language/loops/do...loop>`. However, a <span class="title-ref">Thread</span> does not necessarily yield time at every loop boundary even though it has an opportunity to do so. A <span class="title-ref">Thread</span> actually yields to another <span class="title-ref">Thread</span> when the <span class="title-ref">Thread</span> Scheduler decides that its timeslice has expired. Context switches are expensive, so the <span class="title-ref">Thread</span> Scheduler always tries to avoid them.

You can also force context switches by calling `YieldToNext<thread.yieldtonext>` or by calling `SleepCurrent<thread.sleepcurrent>`.

<div class="note">

<div class="title">

Note

</div>

Code that runs in Threads does not run faster (in fact such code typically runs more slowly because the CPU time is shared as described above). Putting code in a <span class="title-ref">Thread</span> is a way to provide a better user experience by allowing tasks to be perceived as running in the background.

</div>

### Preemptive Threads

Threads, by default, are cooperative. This means that they all run on the same core of the CPU along with the app itself. Therefore they share that resource which means the more processing that core is doing, the longer a cooperative <span class="title-ref">thread</span> will take to complete. Preemptive Threads can run on a core of the CPU separate from other preemptive Threads and separate from the app itself. If a core is available, a preemptive <span class="title-ref">Thread</span> will run on it. Otherwise, it will be run on a core that is also handling other tasks. Thus the advantage of a preemptive <span class="title-ref">Thread</span> is that it can execute potentially far faster than a cooperative <span class="title-ref">Thread</span>.

To create a preemptive <span class="title-ref">Thread</span>, set the `Type<thread.type>` property to Preemptive. You can change the type of a <span class="title-ref">Thread</span> at runtime except when it's running. If it is running, then you can only change it from within the <span class="title-ref">Thread</span> itself.

Most of the Xojo framework is safe for concurrent use with preemptive threads. The notable exceptions are `XojoScript</api/language/xojo_script/xojoscript>` and `Runtime.IterateObjects<runtime.iterateobjects>`, which must not be used in a preemptive <span class="title-ref">Thread</span>.

Be aware that stack overflow checks are not performed on preemptive Threads. If the <span class="title-ref">Thread</span>'s stack overflows, your app will crash.

Do not switch <span class="title-ref">Thread</span> types within a `Semaphore</api/language/threading/semaphore>` lock or `CriticalSection</api/language/threading/criticalsection>`. Doing so will result in the app crashing or becoming locked up.

When modifying shared resources such as `MemoryBlocks</api/data_types/additional_types/memoryblock>`, `Arrays</api/language/array>`, or `Dictionaries</api/language/dictionary>` from multiple threads, use a `Semaphore</api/language/threading/semaphore>` and/or `CriticalSection</api/language/threading/criticalsection>` to ensure that a preemptive <span class="title-ref">Thread</span> is not modifying the resource at the same moment as another <span class="title-ref">Thread</span>. If you are only reading from these resources without modifying them, synchronization is not required.

When used with a preemptive <span class="title-ref">Thread</span>, the `Type<semaphore.type>` property of a `Semaphore</api/language/threading/semaphore>` must also be set to Preemptive. Failing to do this will result in an `IllegalLockingException</api/exceptions/illegallockingexception>`.

A `CriticalSection</api/language/threading/criticalsection>` whose `Type<criticalsection.type>` is set to Cooperative may only be used with a cooperative <span class="title-ref">Thread</span>. If set to Preemptive, it may be used with either a preemptive or cooperative <span class="title-ref">Thread</span>, or both simultaneously.

<div class="warning">

<div class="title">

Warning

</div>

`XojoScript</api/language/xojo_script/xojoscript>` is not safe to use in a preemptive <span class="title-ref">Thread</span>.

</div>

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

### Splitting a Job Across Several Preemptive Threads

Sometimes a job can be made more efficient by spreading it across all the available cores of the CPU. In this case, using multiple prememptive threads is the way to go but that can become unwieldy to manage. The Threadpool example project has a class (Threadpool) that makes this process much simpler.

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

### <span class="title-ref">Android</span> Limitations

- You cannot `Pause<thread.pause>` and `Resume<thread.resume>` Threads.
- You can only set the `Priority<thread.priority>` for preemptive Threads.
- `StackSize<thread.stacksize>` is not supported.
- `Thread.Current<thread.current>` is not currently supported.

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

## Examples

This example uses `StartMethod<thread.startmethod>` to run a method in a <span class="title-ref">Thread</span> without needing a <span class="title-ref">Thread</span> subclass. When *LoadData* finishes, *LoadDataCompleted* is called on the main \`Thread\`:

``` xojo
Thread.StartMethod(AddressOf LoadData, Thread.Types.Preemptive, AddressOf LoadDataCompleted)
```

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

This example shows how to report progress from a <span class="title-ref">Thread</span> to the user interface. The `Run<thread.run>` event calls `AddUserInterfaceUpdate<thread.adduserinterfaceupdate>` as work progresses, and the `UserInterfaceUpdate<thread.userinterfaceupdate>` event updates a `ProgressBar</api/user_interface/desktop/desktopprogressbar>` on the window:

``` xojo
' In the Run event:
For i As Integer = 1 To 100
  ' ... do work here ...
  Me.AddUserInterfaceUpdate("progress" : i)
Next

' In the UserInterfaceUpdate event:
For Each update As Dictionary In data
  If update.HasKey("progress") Then
    ProgressBar1.Value = update.Value("progress")
  End If
Next
```

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

The **Threadpool** example project demonstrates how to spread a job across all available CPU cores using multiple preemptive Threads. It includes a `Threadpool` class that greatly simplifies managing the Threads. See also `Splitting a Job Across Several Preemptive Threads<thread.splitting_a_job_across_several_preemptive_threads>`.

## Compatibility

|                       |     |
|-----------------------|-----|
| **Project Types**     | All |
| **Operating Systems** | All |

<div class="seealso">

`Object</api/data_types/additional_types/object>` parent class; `DesktopApplication</api/user_interface/desktop/desktopapplication>`, `CriticalSection</api/language/threading/criticalsection>`, `Mutex</api/language/threading/mutex>`, `Semaphore</api/language/threading/semaphore>`, `Timer</api/language/timer>`, `WebThread</api/web/webthread>`, `WebTimer</api/web/webtimer>` classes; `Pragma</api/language/pragma_directives>` directives; `ThreadAlreadyRunningException</api/exceptions/threadalreadyrunningexception>`, `ThreadEndException</api/exceptions/threadendexception>`, `ThreadAccessingUIException</api/exceptions/threadaccessinguiexception>`.

</div>
