3

Android provides a Handler class that runs tasks (of type Runnable or Message) serially on a single thread. I am trying to reproduce this exact behavior in a Windows Store App and the only classes I see are ThreadPool and ThreadPoolTimer which I believe provides access to a pool of background threads, but what I want is access to a single background thread.

If it isn't possible with the WinRT API what about with the allowed Win32 API's?

The reason for all this trouble is that I have an old C++ library that is only safe to run on a single thread but I don't want to run it on the UI thread since it could block it. Often times I'd like to queue up a bunch of tasks to have the library execute. Handler in Android was perfect for this.

4

2 回答 2

0

这是我对 Android 处理程序的幼稚实现(至少我已经尽力了):

public class Handler
{
    private static readonly BlockingCollection<Action> queue = new BlockingCollection<Action>();

    static void Loop()
    {
        while (true)
        {
            Action task = queue.Take();

            if (task == null) break;

            task();
        }
    }

    static Handler()
    {
        Thread thread = new Thread(Loop);
        thread.Name = "Handler";
        thread.Start();
    }

    public static void Post(Action task)
    {
        queue.Add(task);
    }
}

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Launching tasks");

        Handler.Post(() => { Console.WriteLine("Running task 1..."); Thread.Sleep(1000); Console.WriteLine("Task 1 done."); });
        Handler.Post(() => { Console.WriteLine("Running task 2..."); Thread.Sleep(3000); Console.WriteLine("Task 2 done."); });
        Handler.Post(() => { Console.WriteLine("Running task 3..."); Thread.Sleep(2000); Console.WriteLine("Task 3 done."); });
        Handler.Post(null);

        Console.WriteLine("Waiting end of tasks");
    }
}

它符合您的需求吗?

于 2013-06-14T00:23:57.620 回答
0

据我所知,答案是否定的,WinRT 没有 Handler 类或明显的替代品。

但是,我能够在 C++/CX 中编写一个 WinRT 类来复制大部分行为。我使用Concurrency::concurrent_queue班级和Windows::System::Threading::ThreadPool班级做到了这一点。基本上,我的 WinRT 处理程序类公开了一个方法,该方法接受 aWindows::System::Threading::WorkItemHandler和 aWindows::Foundation::AsyncActionCompletedHandler并使用队列使用ThreadPool. 当一个工作项完成时,AsyncActionCompletedHandler它被调用。公开的方法返回一个允许用户取消工作的自定义取消令牌对象。如果没有任务正在运行,则立即启动一项,否则将其添加到队列中,当一项完成时,它会查看队列,如果有则启动下一项。

于 2013-06-20T00:07:56.743 回答