C# 对自定义网格中的单元格使用线程
我有一个带有自定义控件的WPF应用程序,比如grid(假设它有100行10列),它在更多的单元格中有公式。 我有自己的逻辑来解析和计算这些单元格中的公式。 它工作正常,但需要更多的时间。 所以我决定使用多线程同时解析单元格 我没有多线程方面的经验。为此,我尝试了线程类和线程池,但我不知道如何实现 这里我提供了我的代码概述C# 对自定义网格中的单元格使用线程,c#,wpf,multithreading,winforms,threadpool,C#,Wpf,Multithreading,Winforms,Threadpool,我有一个带有自定义控件的WPF应用程序,比如grid(假设它有100行10列),它在更多的单元格中有公式。 我有自己的逻辑来解析和计算这些单元格中的公式。 它工作正常,但需要更多的时间。 所以我决定使用多线程同时解析单元格 我没有多线程方面的经验。为此,我尝试了线程类和线程池,但我不知道如何实现 这里我提供了我的代码概述 UpdateCell-->每个单元格的入口点 这里调用-->字符串parsedString=Parse(“cellText”) 请指导我,在哪里可以在UpdateCell或Pa
Public void UpdateCell(object cell)
{
string ParsedString = Parse(grid, cellText);
//How to use threads here? I tried ThreadPool here, but grid gets disposed after thread execution. so that it leads crashing.
//some codes
}
public string Parse(string formulaText)
{
//Parsing logic (How to use threads here? Here i tried threads but it returns empty string immediately.)
return formulaText;
}
谢谢,最好使用任务而不是线程。试试这个代码
public async Task<bool> UpdateCellAsync(object cell)
{
string parsedString = await ParseAsync("cellText");
//if no errors - return true, else - false
return true;
}
public async Task<string> ParseAsync(string formulaText)
{
// if you have async methods, then await methodAsync();
// or create or task/tasks
await Task.Run(() => //your code in separate thread. );
//other stuff to do
return formulaText
}
public异步任务UpdateCellAsync(对象单元格)
{
string parsedString=await ParseAsync(“cellText”);
//如果没有错误-返回true,否则返回false
返回true;
}
公共异步任务ParseAsync(字符串formulaText)
{
//如果您有异步方法,那么等待methodAsync();
//或创建或任务/任务
等待任务。运行(()=>//在单独的线程中运行代码);
//其他要做的事情
返回公式文本
}
我建议您使用任务。下面是我的应用程序中的一个例子@Sasha。用户可以设置解析逻辑的线程数。所以我尝试了线程池。使用线程解析值-我认为这不是最好的主意。阅读这里关于线程和任务之间的区别不要使用线程或任务-不能将它们与用户控件混合使用。访问、更新或创建控件时,只能使用主UI线程。只能对非UI对象使用线程和任务。@Sasha-不能使用UI线程以外的其他线程来更新UI。因此,如果一个任务使用另一个线程,则不能使用它来更新用户控件。