我有两个需要一个接一个地执行的功能。在此函数中,进行异步调用。异步调用完成后如何执行第二个函数?
例如。
public void main()
{
executeFn("1");
executeFn("2"); //I want this to be executed after 1 has finished.
}
private bool executeFn(string someval)
{
runSomeAsyncCode(); //This is some async uploading function that is yet to be defined.
}
答案 0 :(得分:3)
您可以使用Thread.Join。
但是后来我没有看到这两个函数在执行顺序时异步执行的重点。
答案 1 :(得分:1)
让runSomeAsyncCode()
返回IAsyncResult
并实施与CLR Asynchronous Programming Model类似的BeginX
EndX
方法。使用EndX
方法等待代码完成执行。
答案 2 :(得分:0)
你正在调用的异步方法必须有一些东西在完成后通知调用者我是否正确? (否则它只是执行并忘记,这是不可能的)如果是这样,你只需要等待通知出现并执行第二种方法。
答案 3 :(得分:0)
试试这个:
public void main()
{
executeFn("1");
executeFn("2");
}
List<string> QueuedCalls = new List<string>(); // contains the queued items
bool isRunning = false; // indicates if there is an async operation running
private bool executeFn(string someval)
{
if(isRunning) { QueuedCalls.Add(someval); return; } // if there is an operation running, queue the call
else { isRunning = true; } // if there is not an operation running, then update the isRunning property and run the code
runSomeAsyncCode(); //undefined async operation here<-
isRunning = false; //get here when the async is completed, (updates the app telling it this operation is done)
if(QueuedCalls.Count != 0)//check if there is anything in the queue
{
//there is something in the queue, so remove it from the queue and execute it.
string val = QueuedCalls[0];
QueuedCalls.RemoveAt(0);
executeFn(val);
}
}
这种方式将不阻止任何线程,并且只会在第一次芬兰语时执行排队呼叫,这是我认为你想要的!快乐的编码!现在id推荐运行最后一节,在异步操作中将isRunning设置为false,或者在事件或其他事件中触发它,唯一的问题是当你的异步操作完成时必须执行代码。所以你要这样做取决于你
答案 4 :(得分:0)
您可以考虑使用Generic委托执行第一个方法async然后在回调中执行另一个方法async。如果你真的担心执行它们彼此同步。
答案 5 :(得分:0)