如何在不更改签名的情况下将同步方法转换为异步方法

时间:2019-01-07 12:01:40

标签: c# asynchronous task synchronous

我有一个带有40个模块的大型C#解决方案。

我正在尝试将解决方案范围内使用的服务从同步转换为异步。

问题是我无法找到一种方法来更改方法的签名。

我尝试用Task包装上述异步所需的操作,但这需要更改方法签名。

我尝试在方法运行时将调用方更改为阻止自身,但是这使我的系统搞砸了,因为这是一个很长的调用链,并且更改链中的每个成员以阻止自身是一个严重的问题。

public SomeClass Foo()
{
// Synchronous Code
}

将其转换为:

public SomeClass Foo()
{
//Asynchronous code
}

所有呼叫者保持不变

public void DifferentModule()
{
 var class = Foo();
}

3 个答案:

答案 0 :(得分:2)

常见的模式是在方法名称上添加Started GET "/rails/mailers/register_mailer/new_user" for 127.0.0.1 at 2019-01-07 13:33:30 +0100 Processing by Rails::MailersController#preview as HTML Parameters: {"path"=>"register_mailer/new_user"} Completed 500 Internal Server Error in 16ms (ActiveRecord: 0.0ms) NoMethodError (undefined method `show_previews' for ActionMailer::Base:Class): railties (5.2.1) lib/rails/mailers_controller.rb:49:in `show_previews?' activesupport (5.2.1) lib/active_support/callbacks.rb:435:in `block in inverted_lambda' activesupport (5.2.1) lib/active_support/callbacks.rb:178:in `block (2 levels) in halting_and_conditional' activesupport (5.2.1) lib/active_support/callbacks.rb:178:in `each' activesupport (5.2.1) lib/active_support/callbacks.rb:178:in `all?' activesupport (5.2.1) lib/active_support/callbacks.rb:178:in `block in halting_and_conditional' activesupport (5.2.1) lib/active_support/callbacks.rb:513:in `block in invoke_before' activesupport (5.2.1) lib/active_support/callbacks.rb:513:in `each' activesupport (5.2.1) lib/active_support/callbacks.rb:513:in `invoke_before' activesupport (5.2.1) lib/active_support/callbacks.rb:131:in `run_callbacks' actionpack (5.2.1) lib/abstract_controller/callbacks.rb:41:in `process_action' actionpack (5.2.1) lib/action_controller/metal/rescue.rb:22:in `process_action' actionpack (5.2.1) lib/action_controller/metal/instrumentation.rb:34:in `block in process_action' activesupport (5.2.1) lib/active_support/notifications.rb:168:in `block in instrument' activesupport (5.2.1) lib/active_support/notifications/instrumenter.rb:23:in `instrument' activesupport (5.2.1) lib/active_support/notifications.rb:168:in `instrument' actionpack (5.2.1) lib/action_controller/metal/instrumentation.rb:32:in `process_action' actionpack (5.2.1) lib/action_controller/metal/params_wrapper.rb:256:in `process_action' activerecord (5.2.1) lib/active_record/railties/controller_runtime.rb:24:in `process_action' actionpack (5.2.1) lib/abstract_controller/base.rb:134:in `process' actionview (5.2.1) lib/action_view/rendering.rb:32:in `process' actionpack (5.2.1) lib/action_controller/metal.rb:191:in `dispatch' actionpack (5.2.1) lib/action_controller/metal.rb:252:in `dispatch' actionpack (5.2.1) lib/action_dispatch/routing/route_set.rb:52:in `dispatch' actionpack (5.2.1) lib/action_dispatch/routing/route_set.rb:34:in `serve' actionpack (5.2.1) lib/action_dispatch/journey/router.rb:52:in `block in serve' actionpack (5.2.1) lib/action_dispatch/journey/router.rb:35:in `each' actionpack (5.2.1) lib/action_dispatch/journey/router.rb:35:in `serve' actionpack (5.2.1) lib/action_dispatch/routing/route_set.rb:840:in `call' rack (2.0.5) lib/rack/etag.rb:25:in `call' rack (2.0.5) lib/rack/conditional_get.rb:25:in `call' rack (2.0.5) lib/rack/head.rb:12:in `call' activerecord (5.2.1) lib/active_record/migration.rb:559:in `call' actionpack (5.2.1) lib/action_dispatch/middleware/callbacks.rb:28:in `block in call' activesupport (5.2.1) lib/active_support/callbacks.rb:98:in `run_callbacks' actionpack (5.2.1) lib/action_dispatch/middleware/callbacks.rb:26:in `call' actionpack (5.2.1) lib/action_dispatch/middleware/executor.rb:14:in `call' actionpack (5.2.1) lib/action_dispatch/middleware/debug_exceptions.rb:61:in `call' actionpack (5.2.1) lib/action_dispatch/middleware/show_exceptions.rb:33:in `call' railties (5.2.1) lib/rails/rack/logger.rb:38:in `call_app' railties (5.2.1) lib/rails/rack/logger.rb:26:in `block in call' activesupport (5.2.1) lib/active_support/tagged_logging.rb:71:in `block in tagged' activesupport (5.2.1) lib/active_support/tagged_logging.rb:28:in `tagged' activesupport (5.2.1) lib/active_support/tagged_logging.rb:71:in `tagged' railties (5.2.1) lib/rails/rack/logger.rb:26:in `call' actionpack (5.2.1) lib/action_dispatch/middleware/remote_ip.rb:81:in `call' actionpack (5.2.1) lib/action_dispatch/middleware/request_id.rb:27:in `call' rack (2.0.5) lib/rack/runtime.rb:22:in `call' activesupport (5.2.1) lib/active_support/cache/strategy/local_cache_middleware.rb:29:in `call' actionpack (5.2.1) lib/action_dispatch/middleware/executor.rb:14:in `call' actionpack (5.2.1) lib/action_dispatch/middleware/static.rb:127:in `call' rack (2.0.5) lib/rack/sendfile.rb:111:in `call' railties (5.2.1) lib/rails/engine.rb:524:in `call' puma (3.12.0) lib/puma/configuration.rb:225:in `call' puma (3.12.0) lib/puma/server.rb:658:in `handle_request' puma (3.12.0) lib/puma/server.rb:472:in `process_client' puma (3.12.0) lib/puma/server.rb:332:in `block in run' puma (3.12.0) lib/puma/thread_pool.rb:133:in `block in spawn_thread' 并将返回类型包装在Async中。所以:

Task

成为:

public SomeClass Foo()
{
// Synchronous Code
}

您将获得该方法的两个版本,但它将允许您逐步将代码迁移到异步方法,并且在进行迁移时不会破坏现有代码。

答案 1 :(得分:2)

从根本上将内容从同步更改为异步的任何实现都将涉及签名更改。任何其他方法都无法正常工作。从根本上讲:异步和同步需求不同的API,这意味着:不同的签名。这是不可避免的,坦率地说“如何在不更改签名的情况下将同步方法转换为异步方法?”是一个无法解决的问题(很可能是错误的问题)。很抱歉,如果我似乎没有在此处回答问题,但是...有时答案是“您不能,任何说您可以做到的人都在诱使您走上一条非常糟糕的道路”。


async / Task<T>而言,在不破坏兼容性的情况下执行此操作的最常见方法是添加新的/单独的方法,因此您可以

SomeReturnType Foo();

Task<SomeReturnType> FooAsync(); // or ValueTask<T> if often actually synchoronous

这里的FooFooAsync可能没有但不同的实现-一种旨在利用异步的方法,一种可以完全同步工作的方法。通过调用另一个来欺骗一个人不是一个好主意-既“异步同步”(称为异步版本的同步版本)又是“异步同步”(称为同步版本的异步版本) )是反模式,应避免使用(第一种比第二种有害得多)。


如果您真的不想这样做,您也可以执行类似添加FooCompleted回调事件(或类似的事件)的操作,但是:从根本上说,这仍然是一个签名更改,并且调用者仍然必须以其他方式使用API​​。到您完成此操作时-您可能还可以通过添加Task<T> API来简化使用程序。

答案 2 :(得分:0)

如果您迫切需要这样做,可以通过将需要变成 public void AddItemToColumn(int x, Color color1, Color color2) { for (int y = GameInfo.Rows - 1; y >= 0; y--) { if(board._Board[x,y].BackColor == Color.LightGray) { if(GameInfo.board[x,y] == 1) { board._Board[x, y].BackColor = color1; } else if(GameInfo.board[x,y] == 2) { board._Board[x, y].BackColor = color2; } } } } int PlayerTurn = 1; public void AddTokenToArray(int x) { for(int y = GameInfo.Rows-1; y>=0; y--) { if(GameInfo.board[x, y] == 0) { if (PlayerTurn == 1) { GameInfo.board[x, y] = 1; PlayerTurn = 2; break; } else if (PlayerTurn == 2) { GameInfo.board[x, y] = 2; PlayerTurn = 1; break; } } } } 的{​​{1}}代码包装在Synchronous中来实现,方法如下:

Asynchronous

您在Task中编写的代码将异步运行

简短说明::我们使用public SomeClass Foo() { Task t = Task.Run(() => { // Do stuff, code in here will run asynchronously } t.Wait(); // or if you need a return value: var result = t.Wait(); return someClass; // or return result } 开始一个新的Task.Run(() => ...),“ weird”参数是Lambda表达式,基本上是将匿名方法传递给{ {1}}将执行的{1}}方法
然后,我们等待任务以Task t = Task.Run(() => ...)完成。 Task方法可以返回值,您可以像使用任何方法一样,使用Run关键字从匿名方法返回值

注意:这可以但不应这样做。有关更多信息,请参见肖恩的答案