将线程用于自定义网格中的单元格

问题描述 投票:0回答:1

我在WPF应用程序中使用了自定义控件,例如grid(假设它具有100行和10列),并且在更多单元格中具有公式。我有自己的逻辑来逐一解析和计算这些单元格中的公式。它工作正常,但需要更多时间。因此,我决定使用多线程同时解析单元格。

我没有多线程经验。我为此尝试了Thread classThreadPool,但我不知道如何实现。

这里提供了我的代码概述,

  1. UpdateCell->每个单元的入口点
  2. 这里调用->字符串parsedString = Parse(“ cellText”);

[请指导我,在这里我可以在UpdateCell或Parse方法中使用MultiThreading,并在这里帮助我使用Threads或ThreadPool。

    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; 
    }

谢谢,

c# wpf multithreading winforms threadpool
1个回答
-1
投票

最好在线程上使用任务。试试这个代码

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
}
© www.soinside.com 2019 - 2024. All rights reserved.