2012-05-15 8 views
6

यदि निम्न कोड पृष्ठभूमि थ्रेड पर चलाया गया है, तो मैं मुख्य थ्रेड पर 'जारी रखें' कैसे कर सकता हूं?पृष्ठभूमि थ्रेड से शुरू होने पर UI थ्रेड पर कार्य निरंतरता

var task = Task.Factory.StartNew(() => Whatever()); 
    task.ContinueWith(NeedThisMethodToBeOnUiThread), TaskScheduler.FromCurrentSynchronizationContext()) 

उपर्युक्त काम नहीं करेगा, क्योंकि वर्तमान सिंक्रनाइज़ेशन संदर्भ पहले से ही पृष्ठभूमि धागा है।

उत्तर

6

आपको UI थ्रेड से TaskScheduler.FromCurrentSynchronizationContext() का संदर्भ प्राप्त करने और इसे निरंतरता तक पास करने की आवश्यकता है।

इसी तरह के। http://reedcopsey.com/2009/11/17/synchronizing-net-4-tasks-with-the-ui-thread/

private void Form1_Load(object sender, EventArgs e) 
{ 
    // This requires a label titled "label1" on the form... 
    // Get the UI thread's context 
    var context = TaskScheduler.FromCurrentSynchronizationContext(); 

    this.label1.Text = "Starting task..."; 

    // Start a task - this runs on the background thread... 
    Task task = Task.Factory.StartNew(() => 
     { 
      // Do some fake work... 
      double j = 100; 
      Random rand = new Random(); 
      for (int i = 0; i < 10000000; ++i) 
      { 
       j *= rand.NextDouble(); 
      } 

      // It's possible to start a task directly on 
      // the UI thread, but not common... 
      var token = Task.Factory.CancellationToken; 
      Task.Factory.StartNew(() => 
      { 
       this.label1.Text = "Task past first work section..."; 
      }, token, TaskCreationOptions.None, context); 

      // Do a bit more work 
      Thread.Sleep(1000); 
     }) 
     // More commonly, we'll continue a task with a new task on 
     // the UI thread, since this lets us update when our 
     // "work" completes. 
     .ContinueWith(_ => this.label1.Text = "Task Complete!", context); 
} 
+0

मुझे इससे डर था। आपके उत्तर के लिए धन्यवाद। – user981225

संबंधित मुद्दे