J
Why don't you take a look at the solution existing?Examples http://www.albahari.com/threading/ Background Worker♪ Establish a class in which a user code can be applied (e.g. through events or virtual functions): DoWork (both working in the background flow, doing all the work) ProgressChanged (expressed in the main flow, obtains the argument of the current percentage of work performed), WorkCompleted (declared in the main flow, obtains an argument of performance, and a sign of success) provides a function Cancel (which displays a flag which in turn has to be checked by code DoWork)Task♪ An object that is an assignment at present and a result, possibly in the future. The assignment is a user code (delegate but a virtual function/event/what) that reverts to the impactor type and is in a separate flow (in fact, it's a little more complicated but can be ignored for now). Assignment may be " attached " continued Another task that will be performed, for example, in the main flow. The assigned assignments may be different for successful and unsuccessful performance of the core mission, and are obtained at the entrance from the core assignment.C# code:1.var filename = @"C:\A Study in Scarlet.txt";
var bw = new BackgroundWorker
{
WorkerReportsProgress = false,
WorkerSupportsCancellation = false
};
bw.DoWork += (sender, args) =>
{
// in background thread
var lines = File.ReadLines(filename);
var filteredLines = lines.Where(l => l.Contains("Holmes"));
args.Result = filteredLines.Count();
};
bw.RunWorkerCompleted += (sender, args) =>
{
// in UI thread
if (args.Error != null)
ShowError(args.Error.Message);
else
ShowResult(args.Result);
};
bw.RunWorkerAsync();
2.var t = Task.Run(() =>
{
var lines = File.ReadLines(filename);
var filteredLines = lines.Where(l => l.Contains("Holmes"));
return filteredLines.Count();
};
t.ContinueWith(ShowResult,
TaskContinuationOptions.NotOnFaulted,
TaskScheduler.FromCurrentSynchronizationContext());
t.ContinueWith(prev => ShowError(prev.Exception.Message),
TaskContinuationOptions.OnlyOnFaulted,
TaskScheduler.FromCurrentSynchronizationContext());