C#异步问题 - 文件不可用 - 等待其他进程完成

时间:2016-03-18 14:39:46

标签: c# multithreading asynchronous async-await

好的,我有以下程序。当谈到处理proc2时,我得到一个fileLock错误,我认为这是由于proc1仍在处理该文件。如何让proc2等到proc1完成。或者至少在proc1中有一些控制权来等待结果?

private void button1_Click(object sender, EventArgs e)
    {
        String filePath = proc1();
        String result = proc2(filePath);
    }

private String proc1()
{
    // get a filePath
    String filePath = "C:\\Something.xml";
    String APIRequest = "SomeAPIRequest";
    DownloadAPI(filePath, APIRequest);
}

private static async void DownloadAPI(String filePath, String APIRequest, List<String> Parameters = null)
    {
    var client = new HttpClient();

    String APIString = APIRequest + "?ApiKey=" + APIKey;

    // Create the HttpContent for the form to be posted.
    var requestContent = new FormUrlEncodedContent(new[] {
    new KeyValuePair<string, string>("APIKey", APIKey),});

    // Get the response. Check for additional parameters required
    HttpResponseMessage response = null;
    if (Parameters != null)
    {
        foreach (String Parameter in Parameters)
        {
            APIString = APIString + "&" + Parameter;
        }
    }

    response = await client.PostAsync(APIString, requestContent);

    // Get the response content.
    HttpContent responseContent = response.Content;

    StreamWriter file = new System.IO.StreamWriter(filePath);

    // Get the stream of the content.
    using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
    {
        // Write the output.
        file.WriteLine((await reader.ReadToEndAsync()));
    }

    file.Close();
}

private String proc2(String filePath)
{
    // Do stuff with file here
    return "SomeString";
}

3 个答案:

答案 0 :(得分:1)

异步/等待方式:

private async void button1_Click(object sender, EventArgs e) {
    var filePath = await proc1();
    var result = proc2(filePath);
}

private async Task<string> proc1() {
    // get a filePath
    var filePath = "C:\\Something.xml";
    var APIRequest = "SomeAPIRequest";
    await DownloadAPI(filePath, APIRequest);
    return filePath;
}

private static async Task DownloadAPI(string filePath, string APIRequest, List<string> Parameters = null) {
    // ...
}

private string proc2(string filePath) {
    // Do stuff with file here
    return "SomeString";
}

答案 1 :(得分:0)

您需要等待/等待proc1中的DownloadApi调用。否则,在DownloadApi调用完成之前,控制流将继续调用proc2。

答案 2 :(得分:0)

如果它是您正在使用的一个文件,这是一种更经典的等待解决方案。锁定将等到第一个过程完成后再放入第二个过程。

static object lockObj;

public void method()
{
  if(lockObj == null)
      lockObj = new object;

   lock(lockObj)
   {
     //wait your turn sensitive code here.
   }
}