首页 > 解决方案 > 在工作线程中修改字符串然后在主线程中读取结果的正确方法是什么?

问题描述

所以我将一个空字符串从主线程传递给工作线程,然后让工作线程修改字符串,稍后主线程需要能够读取字符串。当然,字符串是按值而不是按引用传递的,因此无法修改。我可以通过传递一个大小为 1 的字符串数组来解决这个问题,但我想知道是否有更简洁的方法来解决这个问题。

//in main thread
    string errorMessage="";
    System.Threading.Thread thread = new System.Threading.Thread(() => { 
        ProcessImport(path, errorMessage); });
    thread.SetApartmentState(System.Threading.ApartmentState.STA);
    thread.Start();

//in worker thread
    if(errorDetected)
    {
        errorMesage= "some message";
    }

//later in main thread
    if(errorMessage!="")
    {
         CreateFeedbackMessageBox(erorrMesssage, 5000);
    }

标签: c#.net-core

解决方案


推荐阅读