One way you could solve this would be to use async and await, like so:
public void Main()
{
AsyncExample();
Console.WriteLine("prints first");
}
public async Task AsyncExample()
{
Task<string> executesSeparately = ExecutesSeparately();
string result = await longRunningTask;
Console.WriteLine(result);
}
public async Task<string> ExecutesSeparately()
{
await Task.Delay(2000);
return "prints second";
}
As you'll see in the output window, Console.WriteLine("prints first") is executed before AsyncExample() completes and writes a line.
Another way you could solve this is by using a BackgroundWorker.
public string DoSomethingQuick()
{
var backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += delegate(object s, DoWorkEventArgs args)
{
DoSomethingThatTakes10Minutes();
};
backgroundWorker.RunWorkerAsync();
return "Process Started";
}
Note that, in a lot of cases, separate threads won't be able to alter non-static objects created from the primary thread, so you'll either need to use the Dispatcher or contain the UI thread logic in a call to BackgroundWorker.ReportProgress(), which automagically works on the UI thread. That would look more like so:
var backgroundWorker = new BackgroundWorker() { WorkerSupportsCancellation = true };
backgroundWorker.ReportProgress += delegate(object s, ProgressChangedEventArgs e)
{
DoSomethingThatTakes10MinutesAndExecutedOnUiThread();
}
backgroundWorker.DoWork += delegate(object s, DoWorkEventArgs e)
{
backgroundWorker.ReportProgress(0); // the progress value is irrelevant
};