为什么在Monotouch中没有TaskScheduler.FromCurrentSynchronizationContext同步?

时间:2012-03-19 16:07:12

标签: c# multithreading xamarin.ios task-parallel-library synchronizationcontext

我感兴趣的是为什么我们需要调用InvokeOnMainThread,而这将是TaskScheduler.FromCurrentSynchronizationContext()的主要意图和责任?。

我正在使用Monotouch中的TPL为iPhone应用程序执行一些后台任务并通过记者类更新UI。但似乎TaskScheduler.FromCurrentSynchronizationContext()没有像你期望的那样同步到UI线程。这时我通过使用Xamarin网站上Threading主题所描述的InvokeOnMainThread设法使其工作(但仍然感觉不对)。

我还在BugZilla上发现了一个报告(类似)bug,似乎已经解决了......另一个threading question关于在MonoTouch中使用后台线程的首选方法。

以下是用于说明我的问题并显示行为的代码段。

    private CancellationTokenSource cancellationTokenSource;

    private void StartBackgroundTask ()
    {
        this.cancellationTokenSource = new CancellationTokenSource ();
        var cancellationToken = this.cancellationTokenSource.Token;
        var progressReporter = new ProgressReporter ();

        int n = 100;
        var uiThreadId = Thread.CurrentThread.ManagedThreadId;
        Console.WriteLine ("Start in thread " + uiThreadId);

        var task = Task.Factory.StartNew (() =>
        {
            for (int i = 0; i != n; ++i) {

                Console.WriteLine ("Work in thread " + Thread.CurrentThread.ManagedThreadId);

                Thread.Sleep (30); 

                progressReporter.ReportProgress (() =>
                {
                    Console.WriteLine ("Reporting in thread {0} (should be {1})",
                        Thread.CurrentThread.ManagedThreadId,
                        uiThreadId);

                    this.progressBar.Progress = (float)(i + 1) / n;
                    this.progressLabel.Text = this.progressBar.Progress.ToString();

                });
            }

            return 42; // Just a mock result
        }, cancellationToken);

        progressReporter.RegisterContinuation (task, () =>
        {
            Console.WriteLine ("Result in thread {0} (should be {1})",
                Thread.CurrentThread.ManagedThreadId,
                uiThreadId);

            this.progressBar.Progress = (float)1;
            this.progressLabel.Text = string.Empty;

            Util.DisplayMessage ("Result","Background task result: " + task.Result);

        });
    }

记者班有这些方法

    public void ReportProgress(Action action)
    {
        this.ReportProgressAsync(action).Wait();
    }
    public Task ReportProgressAsync(Action action)
    {
        return Task.Factory.StartNew(action, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
    }
    public Task RegisterContinuation(Task task, Action action)
    {
        return task.ContinueWith(() => action(), CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
    }
    public Task RegisterContinuation<TResult>(Task<TResult> task, Action action)
    {
        return task.ContinueWith(() => action(), CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
    }

“应用程序输出”窗口中的结果将为:

Start in thread 1
Work in thread 6
Reporting in thread 6 (should be 1)
Work in thread 6
Reporting in thread 6 (should be 1)
...
Result in thread 1 (should be 1)

正如您所见,“在线程6中工作”很好。报告也在线程6上,这是错误的。有趣的是,RegisterContinuation在线程1中进行报告!


进展:我还没有想出这个......有人吗?

2 个答案:

答案 0 :(得分:1)

我认为问题在于您通过执行TaskScheduler.FromCurrentSynchronizationContext()从ProgressReporter类中检索任务计划程序。

您应该将任务计划程序传递到ProgressReporter并改为使用它:

public class ProgressReporter
{
    private readonly TaskScheduler taskScheduler;

    public ProgressReporter(TaskScheduler taskScheduler)
    {
        this.taskScheduler = taskScheduler;
    }

    public Task RegisterContinuation(Task task, Action action)
    {
        return task.ContinueWith(n => action(), CancellationToken.None,
            TaskContinuationOptions.None, taskScheduler);
    }

    // Remaining members...
}

通过将从UI线程获取的任务调度程序传递给进度报告器,您可以确保在UI线程上完成任何报告:

TaskScheduler uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
ProgressReporter progressReporter = new ProgressReporter(uiScheduler);

答案 1 :(得分:0)

您使用的是什么版本的MonoTouch以及它的输出是什么:TaskScheduler.FromCurrentSynchronizationContext()。GetType().ToString()。如果已正确注册上下文,它应该是UIKitSynchronizationContext类型的类。如果这是正确类型的上下文,您是否可以通过直接调用上下文中的Post和Send方法进行快速测试,以查看它们是否最终在正确的线程上执行。你需要启动一些线程池线程来测试它是否正常工作,但它应该相当简单。