簡體   English   中英

如何使用 class 任務 c# 將矩陣和向量相乘

[英]How to multiply matrix and vector using class Task c#

如何使用 class 任務將矩陣乘以向量? 我不明白我可以在我的代碼中究竟在哪里使用任務。 有任何想法嗎?

 public static int[] matxvecTask(int[,] mat, int[] vec) //функция умножения матрицы на вектор Task
{
    Task[] tasks = new Task[4]
    {
        new Task(() => Console.WriteLine("1")),
        new Task(() => Console.WriteLine("2")),
        new Task(() => Console.WriteLine("3")),
        new Task(() => Console.WriteLine("4"))
    };
    foreach(var t in tasks)
    {
        t.Start();
    }
    Task.WaitAll(tasks);
     int[] res = new int[mat.GetLength(0)] ;

         for (int i = 0; i < mat.GetLength(0); i++)
         {
             for (int j = 0; j < mat.GetLength(1); j++)
             {
                 res[i] += mat[i, j] * vec[j];
             }
         }

     return res;
}

老實說,你的問題很不清楚。 無論如何,這段代碼現在使用一個任務。 確保至少使用 C# 7.1,因為Main()方法的使用簽名在以前的語言規范中不是有效的入口點。

internal class Program
{
    private static async Task Main(string[] args)
    {
        int[,] mat = new int[3, 3];
        int[] vec = new int[3];

        int[] result = await Task.Run(() => matxvecAsync(mat, vec));

        Console.WriteLine($"Execution of '{nameof(matxvecAsync)}()' finished");

        Console.ReadLine();
    }

    private static int[] matxvecAsync(int[,] mat, int[] vec)
    {
        int[] res = new int[mat.GetLength(0)];

        for (int i = 0; i < mat.GetLength(0); i++)
        {
            for (int j = 0; j < mat.GetLength(1); j++)
            {
                res[i] += mat[i, j] * vec[j];
            }
        }

        return res;
    }

}

如果您想要更高質量的答案,您需要提供有關您的問題的更多信息。

  • 為什么要使用任務?
  • 你認為你會用它解決你的實際問題嗎?
  • 你對這段代碼有什么要求?
  • 您只是對TAP(基於任務的異步模式)感到好奇嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM