Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
301 views
in Technique[技术] by (71.8m points)

c# - How should I update from Task the UI Thread?

I have a task that performing some heavy work. I need to path it's result to LogContent

Task<Tuple<SupportedComunicationFormats, List<Tuple<TimeSpan, string>>>>.Factory
    .StartNew(() => DoWork(dlg.FileName))
    .ContinueWith(obj => LogContent = obj.Result);

This is the property:

public Tuple<SupportedComunicationFormats, List<Tuple<TimeSpan, string>>> LogContent
{
    get { return _logContent; }
    private set
    {
        _logContent = value;
        if (_logContent != null)
        {
            string entry = string.Format("Recognized {0} log file",_logContent.Item1);
            _traceEntryQueue.AddEntry(Origin.Internal, entry);
        }
    }
}

Problem is that _traceEntryQueue is data bound to UI, and of cause I will have exception on code like this.

So, my question is how to make it work correctly?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is a good article: Parallel Programming: Task Schedulers and Synchronization Context.

Take a look at Task.ContinueWith() method.

Example:

var context = TaskScheduler.FromCurrentSynchronizationContext();
var task = new Task<TResult>(() =>
    {
        TResult r = ...;
        return r;
    });

task.ContinueWith(t =>
    {
        // Update UI (and UI-related data) here: success status.
        // t.Result contains the result.
    },
    CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, context);

task.ContinueWith(t =>
    {
        AggregateException aggregateException = t.Exception;
        aggregateException.Handle(exception => true);
        // Update UI (and UI-related data) here: failed status.
        // t.Exception contains the occured exception.
    },
    CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, context);

task.Start();

Since .NET 4.5 supports async/await keywords (see also Task.Run vs Task.Factory.StartNew):

try
{
    var result = await Task.Run(() => GetResult());
    // Update UI: success.
    // Use the result.
}
catch (Exception ex)
{
    // Update UI: fail.
    // Use the exception.
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...