Execute Task using Serial Executor

There is class which can be called from any thread.

class TicketSubmission {

    func submitTicket(ticketId: String) async {

    }
}

Note here TicketSubmission is not an actor. It will be a simple class.

This can be called from Different tasks.

let submission = TicketSubmission()


Task {

 submission.submitTicket(ticketId: "1")

}

Task {
 submission.submitTicket(ticketId: "2")
}

Task {
 submission.submitTicket(ticketId: "3")
}

How can this made in a way that these execute serially, i.e ticket id 1,2 and 3.

Instead of random ticket being processed serially.

There is a SerialExecutor protocol which can be subclassed. But I am not exactly sure how to use and make sure all of these execute on 1 single task.

1

SerialExecutor is irrelevant, i.e. it does not serialize accesses in some special way.

If submitTicket has no await calls, then it will suffice to make your class an actor:

actor TicketSubmission {
    func submitTicket(ticketId: String) async {

    }
}

You say it is not an actor, but it will need to be one. — If submitTicket does have await calls, then you will have to supply further code to prevent submitTicket from being called while it is already suspended at an await point. This will boil down to a case identical to, e.g. the answer to the question Swift 5.5 Concurrency: how to serialize async Tasks to replace an OperationQueue with maxConcurrentOperationCount = 1?.

Do not be misled by the name: A SerialExecutor is designed to solve a very different problem, namely when you do not want an actor to use the cooperative thread pool. But it sounds like you simply want a series of tasks to run sequentially (with no actor-reentrancy).

I might recommend AsyncChannel from the swift-async-algorithms package. You would have a forawaitin loop monitor the channel, and then you can send ticket identifiers to that channel:

actor TicketService {
    private let channel = AsyncChannel<String>()

    func monitorChannel() async {
        for await ticketId in channel {
            await ticketHandler(ticketId: ticketId)
        }
    }

    func submitTicket(ticketId: String) async {
        await channel.send(ticketId)
    }
}

private extension TicketService {
    func ticketHandler(ticketId: String) async {
        try? await Task.sleep(for: .seconds(1))
    }
}

And you would monitorChannel when the app starts, have submitTicket send ticket identifiers, and ticketHandler will process them one at a time. For example, in SwiftUI:

struct DetailView: View {
    let service = TicketService()
    @State var id = 0

    var body: some View {
        VStack {
            Button("Submit") {
                id += 1

                Task {
                    await service.submitTicket(ticketId: "(id)")
                }
            }
        }
        .padding()
        .task {
            await service.monitorChannel()
        }
    }
}

Yielding:

So, you can follow what is going on in this timeline, the Ⓢ signposts are where I clicked the button to submit a new ticket, but you can see the ticketHandler lane in this “Points of Interest” graph will process them one at a time.

In this run, represented by the above “Points of Interest” timeline:

  • I clicked three times (faster than ticketHandler could run them) … demonstrating that it handles these sequentially while the UI remains responsive;
  • I waited until they finished, and clicked one more time … demonstrating that if there were no going, that this fourth ticket was handled immediately;
  • I then dismissed the view (canceling the monitoring of the channel) … demonstrating that you can cancel this channel, if that is desired;
  • I then re-entered the view in question and clicked 9 times in quick succession, but then canceled all of this before they finished … demonstrating cancelation of the channel in progress.

In the above code snippets, I omitted the Instruments’ “Points of Interest” instrumentation to avoid distracting you with code unrelated to your question at hand. But here is the complete MRE:

import os.log
import AsyncAlgorithms

let poi = OSSignposter(subsystem: "TicketService", category: .pointsOfInterest)

actor TicketService {
    private let channel = AsyncChannel<String>()

    func monitorChannel() async {
        let state = poi.beginInterval(#function, id: poi.makeSignpostID())
        defer { poi.endInterval(#function, state) }

        for await ticketId in channel {
            await ticketHandler(ticketId: ticketId)
        }
    }

    func submitTicket(ticketId: String) async {
        let state = poi.beginInterval(#function, id: poi.makeSignpostID(), "(ticketId)")
        defer { poi.endInterval(#function, state, "(ticketId)") }
        await channel.send(ticketId)
    }
}

private extension TicketService {
    func ticketHandler(ticketId: String) async {
        let state = poi.beginInterval(#function, id: poi.makeSignpostID(), "(ticketId)")
        defer { poi.endInterval(#function, state, "(ticketId)") }

        try? await Task.sleep(for: .seconds(1))
    }
}

And:

struct DetailView: View {
    let service = TicketService()
    @State var id = 0

    var body: some View {
        VStack {
            Button("Submit") {
                id += 1
                poi.emitEvent("Click", "(id)")

                Task {
                    await service.submitTicket(ticketId: "(id)")
                }
            }
        }
        .padding()
        .task {
            await service.monitorChannel()
        }
    }
}

I then profiled this with Instruments, selected the “Time Profiler” template, and then started the recording.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật