Kei000
Kei000

Reputation: 11

Threads don't behave properly, c#

I have been trying to use multithreading lately to speed up my codes, but it hasn't been going great.

I have this simple logic in the code I'm currently developing:

Start Main Code
{
    //code
    Thread thread1 = new Thread(() => {list1 = Method1();});
    thread1.Start();
    Thread thread2 = new Thread(() => {list2 = Method2();});
    thread2.Start();
    //more code
    thread1.Join();
    ListA = list1;
    thread2.Join();
    ListB = list2;
    return whatever;
}

I would expect that thread1 and thread2 run alongside the main code and then meet at the Join()'s, but for some reason my code jumps all over and gets to the return statement seemingly randomly, without even going trough the entire main code.

Is there something I'm missing here?

Edit:

I´m sorry for not being clear in my question. What I mean is this:

Code starts at line 1, as expected, then runs normally until it meets the Thread.Start()'s I declared. Then it countinues to run normally for a few more lines, until suddenly it jumps straigth to the "return whatever" line at the end of the main code block.

I know that when debugging this kind of code it jumps all over the methods I create, that is not the problem I face. The problem, as I mentioned, is the out of the blue jump to the end of the code.

I'm using .NET Framework 4.5.1.

Upvotes: 1

Views: 100

Answers (1)

Joakim
Joakim

Reputation: 2217

Since you haven‘t specified which version of the .NET framework, I am going to assume you can use the async framework. This code will run both tasks in parallel if need be and should only take as long as the longest task you have. Instead of Task.Delay() you would have your own code which actually goes to the db and retrieve the data.

(Running version of the code below https://dotnetfiddle.net/CCCfKw)

using System;
using System.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;

public class Program
{
    public static void Main()
    {
        var doWork = new SomeWorkClass();

        var list1Task = doWork.GetList1Async();
        var list2Task = doWork.GetList2Async();

        var list1 = list1Task.Result;
        var list2 = list2Task.Result;

        var newList = list1.Concat(list2).ToList();

        foreach(var str in newList) {
            Console.WriteLine(str);
        }
    }
}

public class SomeWorkClass
{
    private List<string> _list1 = new List<string>() { "Some text 1", "Some other text 2" };
    private List<string> _list2 = new List<string>() { "Yet more text 3" };

    public async Task<List<string>> GetList1Async()
    {
        await Task.Delay(1000);
        return _list1;
    }

    public async Task<List<string>> GetList2Async()
    {
        await Task.Delay(700);
        return _list2;
    }
}

Upvotes: 1

Related Questions