task

package module
v0.0.0-...-47fdd8c Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 2, 2022 License: MIT Imports: 2 Imported by: 0

README

go-tasks

C# Task wrapper for Go

How to use it:

package main

import (
	task "github.com/mihailpw/go-tasks"
	"time"
)

func main() {
	// Create 3 tasks
	t1 := task.Run(func() error { return do("Do1", 2000) })
	t2 := task.Run(func() error { return do("Do2", 3000) })
	t3 := task.Run(func() error { return do("Do3", 1000) })

	// WaitAny() waits for first finished task and returns it as a result
	firstCompleted := task.WaitAny(t1, t2, t3)
	println("After WaitAny()")

	// Verify that WaitAny returns correct task
	switch *firstCompleted {
	case t1:
		println("t1 completed earlier others")
	case t2:
		println("t2 completed earlier others")
	case t3:
		println("t3 completed earlier others")
	}

	// Task.Await() waits for task completion
	t1.Await()
	println("After t1.Await()")

	// WaitAll() waits for all tasks completion
	task.WaitAll(t1, t2, t3)
	println("After WaitAll()")

	t2.Await()
	println("After t2.Await()")
	t3.Await()
	println("After t3.Await()")
}

func do(str string, ms uint) error {
	time.Sleep(time.Duration(ms) * time.Millisecond)
	println(str, "done after", ms, "ms")
	return nil
}

As a result in console you will see next:

Do3 done after 1000 ms
After WaitAny()
t3 completed earlier others
Do1 done after 2000 ms
After t1.Await()
Do2 done after 3000 ms
After WaitAll()
After t2.Await()
After t3.Await()

Documentation

Index

Constants

View Source
const (
	StateCreated  State = "Created"
	StateRunning        = "Running"
	StateFinished       = "Finished"
)

Variables

This section is empty.

Functions

func WaitAll

func WaitAll(tasks ...Awaitable)

Types

type Awaitable

type Awaitable interface {
	IsCompleted() bool
	Await() error
}

func WaitAny

func WaitAny(tasks ...Awaitable) *Awaitable

type State

type State string

type Task

type Task[T any] struct {
	State  State
	Result *T
	Error  error
	// contains filtered or unexported fields
}

func Run

func Run(f func() error) *Task[types.Nil]

func RunT

func RunT[T any](f func() (*T, error)) *Task[T]

func (*Task[T]) Await

func (t *Task[T]) Await() error

func (*Task[T]) IsCompleted

func (t *Task[T]) IsCompleted() bool

type TaskCompletionSource

type TaskCompletionSource[T any] struct {
	IsDone bool
	Value  *T
	// contains filtered or unexported fields
}

func NewTaskCompetitionSource

func NewTaskCompetitionSource[T any]() *TaskCompletionSource[T]

func (*TaskCompletionSource[T]) Await

func (tcs *TaskCompletionSource[T]) Await() error

func (*TaskCompletionSource[T]) Complete

func (tcs *TaskCompletionSource[T]) Complete(value *T)

func (*TaskCompletionSource[T]) IsCompleted

func (tcs *TaskCompletionSource[T]) IsCompleted() bool

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL