मुझे लगता है कि आपका उत्तर कॉलबैक है।
अपने लंबे समय से चलने वाले धागे को सेट करते समय, किसी विधि के संदर्भ में पास करें। आप या तो कॉलबैक विधि को कार्य विधि में पास कर सकते हैं, या आप एक AsyncCallback प्रतिनिधि उदाहरण स्थापित कर सकते हैं, जो प्रतिनिधियों की BeginInvoke() सुविधा में बनाया गया है।
यहाँ एक बुनियादी उदाहरण है:
public void StartMyTwoTasks()
{
//I'm passing the callback to the task method directly; you may prefer to pass it to BeginInvoke()
var task1Lambda =()=>Task1(TaskCompleted);
var task2Lambda =()=>Task2(TaskCompleted);
task1Lambda.BeginInvoke(null,null);
task2Lambda.BeginInvoke(null,null);
}
public void Task1(Action<int> task1Complete)
{
//perform your long-running calculation or data retrieval/transformation here
Thread.Sleep(10000);
//when finished, call the callback method.
//You may need to use Control.Invoke() to make sure the callback is executed on the UI thread
//If you use the AsyncCallback feature of BeginInvoke/EndInvoke, you don't have to make the call here.
taskComplete(1);
}
public void Task2(Action<int> taskComplete)
{
//Ditto
Thread.Sleep(8000);
taskComplete(2);
}
public void Task1Complete(int taskNumber)
{
TasksComplete[taskNumber-1] = true;
If(TasksComplete.All(x=>x==true))
DoSomethingOnceAllTasksAreComplete();
}
AsyncCallback सुविधा का उपयोग, अपने कॉलबैक विधि एक विशेष प्रतिनिधि परिभाषा यह है कि IAsyncResult स्वीकार करता है के अनुरूप है, लेकिन आप में ठीक से लागू बारे में चिंता करने की जरूरत नहीं है आपकी विधि; ढांचा आपके लिए कॉलबैक को संभालता है:
public public void StartALongTask()
{
var taskLambda =()=>PerformTask();
taskLambda.BeginInvoke(TaskComplete,null);
}
//one advantage is that you can call a method that returns a value very easily.
public IEnumerable<string> PerformTask()
{
//long-running task
Thread.Sleep(5000);
return Enumerable.Repeat("result", 100);
//look ma, no callback invocation.
//This makes asynchronous delegates very useful for refactoring a synchronous
//operation without a lot of code changes.
}
//Here's the callback, which is invoked properly by the runtime when the thread is complete
public void TaskComplete(IASyncResult ar)
{
//calling EndInvoke on the same delegate, which is available in the AsyncResult,
//returns the return value of that delegate as if you'd called it synchronously.
var results = ar.AsyncDelegate.EndInvoke(ar);
//Now you can do something with those results.
}
इन दोनों मॉडलों को आपके लिए ठीक काम करना चाहिए। अन्य विकल्पों में एक ईवेंट स्थापित करना शामिल है, जिसे तब पूरा होने पर प्रत्येक विधि द्वारा उठाया जाता है। यह काफी समान तरीके से काम करेगा, क्योंकि घटनाएं वास्तव में कुछ वाक्यविन्यास चीनी के साथ "बहु-कलाकार" प्रतिनिधि हैं।
यह वही है जो मैं ढूंढ रहा हूं। मुझे संदेह था कि ढांचे में ऐसा कुछ था, मुझे बस यह नहीं मिला। – Mas