2

您将如何使用 C# 中的最新线程技术重写它?

var dateRange = new DateRange(date, date.AddDays(1));
var extracter = new ConversionsExtracter(dateRange, AdvertiserId);
var loader = new ConversionsLoader();
var extracterThread = extracter.Start();
var loaderThread = loader.Start(extracter);
extracterThread.Join();
loaderThread.Join();

loader 和 extract 对象都有一个Start方法:

public  Thread Start()
{
    var thread = new Thread(Extract);
    thread.Start();
    return thread;
}
4

2 回答 2

11

有任务:

var t1 = Task.Factory.StartNew(() => extracter.Start(), TaskCreationOptions.LongRunning);
var t2 = Task.Factory.StartNew(() => loader.Start(), TaskCreationOptions.LongRunning);

// some arbitrary amount of code here that's executed on the main thread.

// Wait for both threads to complete before continuing.
t1.Wait();
t2.Wait();

// Code here cannot execute until the loader and extractor are finished.

与显式管理线程相比,任务具有许多使它们更易于使用的功能,包括支持取消、继续等。非常值得研究。

于 2013-07-26T03:13:37.593 回答
0

使用这个定义的方法:

async Task<TResult> RunLoadAsync(/* args */) {
  var dateRange = new DateRange(date, date.AddDays(1));
  var extracter = new ConversionsExtracter(dateRange, AdvertiserId);
  var loader    = new ConversionsLoader();

  var intermediate = await Task.Factory.StartNew(
      () => extracter.Start(), TaskCreationOptions.LongRunning
  );
  return await Task.Factory.StartNew(
      () => loader.Start(intermediate), TaskCreationOptions.LongRunning
  );
}

像这样调用它:

   var result = await RunLoadAsync(/* parameters */);

更新:这是一个更完整的用法示例:

private async void PanelBoard_MouseCtlClick(object sender, HexEventArgs e) {
  GoalHex = e.Coords;
  // other processing to prepare.
  try { Path = await MapBoard.GetDirectedPathAsync(MapBoard[StartHex], MapBoard[GoalHex]); } 
  catch (OperationCanceledException) { Path = default(IDirectedPath); }
}

public static async Task<IDirectedPath> GetDirectedPathAsync(
  this IBoard<IHex> @this, 
  IHex start,  IHex goal
) {
  if (@this == null) throw new ArgumentNullException("this");
  return @this.GetDirectedPath(start, goal);
}

IDirectedPath Path {
  set { /* code here to refresh display when Path is ready */ }
}

public static Task<IDirectedPath> GetDirectedPathAsync(
  this IBoard<IHex> @this, 
  IHex start,  IHex goal
) {
  if (@this == null) throw new ArgumentNullException("this");
  return Task.Run<IDirectedPath>(
      () => @this.GetDirectedPath(start, goal)
  );
}

方法GetDirectedPathAsync()上的async限定符使其成为await的对象。

于 2013-07-26T03:49:30.480 回答