简体   繁体   English

如何在c#中将参数传递给异步任务

[英]How to pass parameter to asynchronous task in c#

During an ASP.NET web request I need to kick off an asynchronous task and then return control back to the web page. 在ASP.NET Web请求期间,我需要启动异步任务,然后将控制权返回到网页。 Can someone show me the code for calling the below method? 有人可以告诉我调用以下方法的代码吗? Just to be clear, I want the function called async and the web request to complete returning control to the calling page while the function is still processing. 为了清楚起见,我希望在函数仍在处理时,调用async和web请求的函数完成对控制页面的返回控制。

private void FunctionToCall(IInterface objectIWantToPassIn)
{
   // do stuff
}

You'll want to spawn the thread by creating a 你想通过创建一个来生成线程

Task task = Task.Factory.StartNew(action, "arg");

then you'll want to do something maybe when the task is done: 然后你可能想要在任务完成时做一些事情:

task.ContinueWith(anotheraction);

Of course action and otheraction would be void methods in this case. 当然,在这种情况下,行动和剥夺将是无效的方法。

 private void FunctionToCall(object state)
 {
        IInterface objectIWantToPassIn= (IInterface ) state;
        // do stuff
 }

  System.Threading.ThreadPool.QueueUserWorkItem(FunctionToCall, 
                                                objectIWantToPassIn);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM