使用任务访问UI元素

时间:2015-11-30 19:18:56

标签: c# .net multithreading task-parallel-library task

我有以下启动方法,它实际上启动了一个任务:

    [STAThread]
    public void Start()
    {
        if (!this.cancellationToken.IsCancellationRequested)
        {                
            SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
            this.t = Task.Factory.StartNew(
            () =>
            {
                var grid = new Grid
                {
                    Width = 200,
                    Height = 2000
                };                       
            }, 
            this.cancellationToken, 
            TaskCreationOptions.None, 
            TaskScheduler.FromCurrentSynchronizationContext());
            this.log.LogDebug(string.Format(CultureInfo.InvariantCulture, "Task " + this.TaskId + " is started"));
        }
        else
        {
            this.log.LogDebug(string.Format(CultureInfo.InvariantCulture, "Cancellation is requested, Task " + this.TaskId + " will not start"));
        }          
    }

我已将TaskScheduler定义为&#34; FromCurrentSynchronizationContext,因为我希望任务执行并访问UI元素(Grid)以检查它是否具有权限,但我收到以下错误:< / p>

The calling thread must be STA, because many UI components require this

我认为它可以通过将TaskScheduler设置为&#34; FromSynchronizationContext&#34;来实现,但没有运气。在这种情况下问题在哪里?

1 个答案:

答案 0 :(得分:-1)

只需删除此行:

SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());

已在GUI应用程序中设置SynchronizationContext

请注意,您可以从[STAThread]方法中删除Start属性,因为此处不执行任何操作。此属性仅在应用程序的入口点有效,即main方法。