In the task, why does IProgress <T> execute correctly in the user interface thread but not Action <T>?

In the following code snippet:

Task UpdateMedias<TProperty>(Expression<Func<Media, TProperty>> property, Func<Media, TProperty> func)
{
    var medias = GetSelectedMedias().ToList();
    IProgress<double> progress = new Progress<double>(d => barQueueProgress.EditValue = d);
    Action<Media, Expression<Func<Media, TProperty>>, Func<Media, TProperty>> action =
        (media, expression, arg3) => UpdateMedia(media, expression, arg3);
    Task task = Task.Run(() =>
    {
        var i = 0;
        foreach (var media in medias)
        {
            progress.Report(1.0d / medias.Count * ++i);
            action(media, property, func);
        }
    });
    Task with = task.ContinueWith(s =>
    {
        progress.Report(0.0d);
        GridControl1.RefreshData();
    });
    return with;
}

If I do not cover actionwith help Dispatcher.BeginInvoke, he will complain. The calling thread cannot access this object because another thread belongs to it. but for progressthere is no need to do it.

Why IProgress<T>does it work unnecessarily Dispatcher.BeginInvoke?

+3
source share
1 answer

Since the Progresslink to what was in SynchronizationContext.Currentwhen it was created is stored inside , and it fires an event in this context when presenting a report on the achieved results.

, UI. , , .

Progress pre.NET 4.5. .NET, , :

public interface IProgress<T>
{
    void Report(T data);
}

public class Progress<T> : IProgress<T>
{
    SynchronizationContext context;
    public Progress()
    {
        context = SynchronizationContext.Current
            ?? new SynchronizationContext();
    }

    public Progress(Action<T> action)
        : this()
    {
        ProgressReported += action;
    }

    public event Action<T> ProgressReported;

    void IProgress<T>.Report(T data)
    {
        var action = ProgressReported;
        if (action != null)
        {
            context.Post(arg => action((T)arg), data);
        }
    }
}
+8

All Articles