आप Task
का उपयोग कर सकते हैं। आप अपने कोड का अन्य भाग निर्दिष्ट नहीं करते हैं, इसलिए मुझे नहीं पता कि आप क्या करना चाहते हैं। मैं आपको सलाह देता हूं कि Task.Wait
का उपयोग करने से बचें क्योंकि यह यूआई थ्रेड को अवरुद्ध कर रहा है और कार्य को समाप्त करने की प्रतीक्षा कर रहा है, जो वास्तव में असीमित नहीं बन गया है! यदि आप कार्य में फ़ाइल को पढ़ने के बाद कुछ अन्य कार्य करना चाहते हैं, तो आप task.ContinueWith
का उपयोग कर सकते हैं।
यहाँ पूर्ण उदाहरण के लिए, कैसे यूआई धागा
static void Main(string[] args)
{
string filePath = @"FILE PATH";
Task<string[]> task = Task.Run<string[]>(() => ReadFile(filePath));
bool stopWhile = false;
//if you want to not block the UI with Task.Wait() for the result
// and you want to perform some other operations with the already read file
Task continueTask = task.ContinueWith((x) => {
string[] result = x.Result; //result of readed file
foreach(var a in result)
{
Console.WriteLine(a);
}
stopWhile = true;
});
//here do other actions not related with the result of the file content
while(!stopWhile)
{
Console.WriteLine("TEST");
}
}
public static string[] ReadFile(string filePath)
{
List<String> lines = new List<String>();
string line = "";
using (StreamReader sr = new StreamReader(filePath))
{
while ((line = sr.ReadLine()) != null)
lines.Add(line);
}
Console.WriteLine("File Readed");
return lines.ToArray();
}
तुम सिर्फ एक पृष्ठभूमि सूत्र में पढ़ने कर सकता को रोके बिना यह करने के लिए। .NET 4 में अभी भी टीपीएल, थ्रेड्स और पृष्ठभूमिवर्कर्स हैं। –
आपका प्रश्न अस्पष्ट है। 'ReadLineAsync()' मुख्य रूप से उपयोगी है यदि आपके पास अन्य संबंधित सुविधाएं हैं, विशेष रूप से 'async'/'await'। क्या आप .NET 4.0 के लिए Async CTP या Async लक्ष्यीकरण पैक का उपयोग कर रहे हैं? यदि नहीं, तो 'ReadLineAsync() 'जैसी विधि का उपयोग करने के लिए आपकी योजना क्या है? ध्यान दें कि यदि .NET के पास पहले से ही 'ReadLineAsync()' जैसा कुछ था, तो शायद वे इसे 4.5 में जोड़ नहीं पाएंगे। आप या किसी और को लिखना होगा, या इसे पहले से ही लिखना होगा। –
यदि आप चाहते हैं कि 'ReadLineAsync()' _some_ कार्यान्वयन है, तो आप केवल [.NET संस्करण 4.5 से कॉपी कर सकते हैं] (https://referencesource.microsoft.com/#mscorlib/system/io/streamreader.cs,884afa7bffa068d0)। यह सब के बाद, खुला स्रोत है। –